<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/3/1
 * Time: 10:50
 */

namespace zhtfrontend\controllers;

use common\components\extenders\AjaxObject;
use common\components\extenders\RequestManage;
use common\components\helpers\Fun;
use common\components\helpers\Util;
use common\components\services\customer\Account;
use common\components\services\customer\Createcard;
use common\components\services\msg\MsgBehavior;
use common\components\services\message\WechatMessage;
use common\components\services\orders\Oper;
use common\components\services\orders\ZhtOper;
use common\models\datas\Card;
use common\models\datas\CardAttr;
use common\models\datas\CardBatch;
use common\models\datas\CardReSend;
use common\models\datas\CardSend;
use common\models\datas\Category;
use common\models\datas\Customer;
use common\models\datas\CustomerBranchaccount;
use common\models\datas\CustomerDues;
use common\models\datas\Customergrade;
use common\models\datas\CustomerRegisterRelation;
use common\models\datas\Recharge;
use common\models\datas\Setting;
use doumiaoduo\buildform\BuildForm;
use zhtfrontend\components\bases\BaseController;
use zhtfrontend\components\helpers\Funs;
use zhtfrontend\components\services\classmanager\Operclassmanager;
use zhtfrontend\components\services\commission\Commission;
use zhtfrontend\components\services\commission\MechanicCommission;
use zhtfrontend\components\services\customer\Checkclassroom;
use zhtfrontend\components\services\customer\Opercustomer;
use zhtfrontend\components\services\message\ProceduresAction;
use zhtfrontend\components\services\orders\Operorders;
use zhtfrontend\models\datas\ArtTeaching;
use zhtfrontend\models\datas\ClassLesson;
use zhtfrontend\models\datas\ClassManage;
use zhtfrontend\models\datas\ClassManageAttribute;
use zhtfrontend\models\datas\ClassManageGoods;
use zhtfrontend\models\datas\Classroom;
use zhtfrontend\models\datas\ClassStudent;
use common\models\datas\DepositLog;
use zhtfrontend\models\datas\Coupons;
use zhtfrontend\models\datas\Course;
use zhtfrontend\models\datas\CustomerCoupons;
use zhtfrontend\models\datas\FullActivities;
use zhtfrontend\models\datas\Goods;
use zhtfrontend\models\datas\GoodsAttr;
use zhtfrontend\models\datas\GoodsClassTime;
use zhtfrontend\models\datas\GoodsGroup;
use zhtfrontend\models\datas\GoodsPrice;
use zhtfrontend\models\datas\GoodsTeacher;
use zhtfrontend\models\datas\LessonStudent;
use zhtfrontend\models\datas\Order;
use zhtfrontend\models\datas\OrdercourseHistory;
use zhtfrontend\models\datas\OrderHistory;
use zhtfrontend\models\datas\Orders;
use zhtfrontend\models\datas\OrderSales;
use zhtfrontend\models\datas\OrdersCommission;
use zhtfrontend\models\datas\OrdersCouponsHistory;
use zhtfrontend\models\datas\OrdersItems;
use zhtfrontend\models\datas\OrdersItemsRelation;
use zhtfrontend\models\datas\OrdersSquarePaymethod;
use zhtfrontend\models\datas\OrdersType;
use zhtfrontend\models\datas\Sales;
use common\models\datas\Student;
use zhtfrontend\models\datas\StudentCheck;
use zhtfrontend\models\datas\Teacher;
use yii\base\ErrorException;
use yii\db\Query;
use yii\helpers\Html;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\data\Pagination;
use yii\helpers\Json;
use yii\web\BadRequestHttpException;
use yii\widgets\ActiveForm;
use moonland\phpexcel\Excel;
use common\components\actions\DeleteAction;
use common\models\datas\AccountRecord;
use yii\helpers\ArrayHelper;
use common\components\helpers\Tree;
use dosamigos\qrcode\QrCode;


class CustomerController extends BaseController
{
    public function init()
    {
        parent::init(); // TODO: Change the autogenerated stub
        //$capaction = new TelecaptchaAction();
        //$capaction->attachBehavior("message",new MessageBehavior());

    }

    public function actionIndex()
    {
        $site_id = Fun::getSiteId();
        $param = \Yii::$app->request->get();
        $model = [];
        $pageSize =  12;
        $data = CustomerRegisterRelation::find()
            ->from('{{%customer_register_relation}} crr')
            ->leftJoin('{{%customer}} c', 'crr.customer_id = c.id')
            ->where(['crr.site_id' => $site_id])
            ->orderBy('crr.customer_id DESC');
        if (!empty($param)) {
            $search_data = array_filter($param);
            if (!empty($search_data['year']) && !empty($search_data['mouth'])) {
                if ($search_data['types'] == 2) {
                    $time = $search_data['year'] . "-" . $search_data['mouth'];
                    $end = Fun::getCurMonthLastDay($time);
                    $data->andWhere(['<=', 'c.created_at', $end]);
                } else {
                    $time = $search_data['year'] . "-" . $search_data['mouth'];
                    $start = Fun::getCurMonthFirstDay($time);
                    $end = Fun::getCurMonthLastDay($time);
                    $data->andWhere(['between', 'c.created_at', $start, $end]);
                }
            }

            if (!empty($search_data['tel'])) {
                $data->andWhere(['c.mobile' => $search_data['tel']]);//tel字段改为mobile
            }
            if (!empty($search_data['name'])) {
                $data->andWhere(['c.name' => $search_data['name']]);
            }
            if (!empty($search_data['card_id'])) {
                $data->andWhere(['c.card_id' => $search_data['card_id']]);
            }
            if (!empty($search_data['customer_status'])) {
                $cids = Customer::find()->select('id')->where(['grade_id' => $search_data['customer_status']])->andwhere(['site_id' => $site_id])->column();
                $data->andWhere(['c.id' => $cids]);
            }
        }
        $auth = \Yii::$app->authManager;
        $roles = $auth->getRolesByUser(\Yii::$app->user->id);
        $arr = [];
        if(!empty($roles)){
            foreach ($roles as $item){
                $arr[] = $item->name;
            }
        }
        if (isset(\Yii::$app->user->identity) && \Yii::$app->user->identity->role == 'mechanic') {
            $data->andWhere(['c.mechanic_id' => \Yii::$app->user->identity->mechanic_id]);
        }
        if (isset(\Yii::$app->user->identity) && in_array(\Yii::$app->user->identity->role, ['admin', 'administrator'])) {
            $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $pageSize,'params'=>$param,'pageSizeParam'=>false]);
            isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;
            $model = $data->offset($pages->offset)->limit($pages->limit)->all();
        } else {
            $pages = new Pagination(['totalCount' => 0, 'pageSize' => $pageSize]);
            if (!empty($param['tel']) || !empty($param['name']) || !empty($param['card_id'])) {
                $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $pageSize, 'params' => $param, 'pageSizeParam' => false]);
                isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;
                $model = $data->offset($pages->offset)->limit($pages->limit)->all();
            }
        }
        $array = Fun::asArray($model, ['name', 'age', 'sex', 'mobile', 'card_id', 'operate', 'grade', 'account', 'is_sender', 'email', 'integral']);

        $grade = Customergrade::find()->where(['is_delete' => 0])->all();
        $list = [];
        foreach ($grade as $k => $v) {
            $list[null] = '请选择';
            $list[$v->id] = $v->name;
        }
        return $this->render('index', ['list' => $list, 'data' => $array, 'pages' => $pages]);
    }

    public function actionQuery()
    {
        if (\Yii::$app->user->identity->role == 'cashier') {
            $this->layout = '@app/views/layouts/iframe2.php';
        }
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'card') {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $card = \Yii::$app->request->post('card');
            $model = Customer::find()->where(['card_id' => $card])->orWhere(['mobile' => $card])->one();
            $Register = null;
            if ($model != null) {
                $Register = CustomerRegisterRelation::find()->where(['site_id' => Fun::getSiteId(), 'customer_id' => $model->id])->one();
            }
            $data['status'] = 0;
            if ($model != null && $Register != null) {
                $data['status'] = 1;
                $data['id'] = $model->id;
            }
            return $data;
        }
        return $this->render('query');
    }


    public function actionCreate()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $model = new Customer();
        $model->scenario = 'create';
        $model->site_id = Fun::getSiteId();
        $model->age = '';
        $form = new BuildForm('@app/components/forms/customerForm.php');
        //remove qrcode by xiaofeng| 20151224$model->check_book = 1;
        $form->loadModel(['customer' => $model]);
        $site_id = Fun::getSiteId();

        //添加会员等级的选择
        $cusgrades = Customergrade::find()->where(['is_delete' => 0])->asArray()->all();
        $form->setItems('customer', 'grade_id', ArrayHelper::map($cusgrades, 'id', 'name'));
        $now_year = (int)date('Y');
        $oldyear = $now_year - 70;
        $years = range($oldyear, $now_year);
        $arr = [];
        foreach ($years as $y) {
            $arr[$y] = $y;
        }
        $form->setItems('customer', 'age', $arr);
        $form->loadDefaultValues();
        //ajax 验证操作,
        /**if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax')=='customer-form' && $form->loadData(\Yii::$app->request->post())) {
         * \Yii::$app->response->format = Response::FORMAT_JSON;
         * return $form->ajaxValidate();
         * }*/
        if (\Yii::$app->request->post('ajax') == 'customer-form' && $form->loadData(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($form->loadData(\Yii::$app->request->post()) && $form->validate()) {
            //remove qrcode by xiaofeng| 20151224
            $model = $form->getModel('customer');
            /*
             * 遍历数据库表中是否已经存在手机号对应的记录，如果存在执行更新操作；
             * 否则执行保存插入操作
             */
            $telephone = $model->mobile;//tel字段改为modile
            $customer = Customer::find()->where(['mobile' => $telephone])->one();//tel字段改为modile
            $model->password = \Yii::$app->security->generatePasswordHash($model->password);
            if ($customer != null && !empty($customer->id)) {
                $customer->attributes = $model->attributes;
            }
            if ($customer != null) {
                if ($customer->save(false)) {
                    $cr = CustomerRegisterRelation::find()->where(['site_id' => $site_id, 'customer_id' => $customer->id])->one();
                    if ($cr == null) {
                        $CustomerRegisterRelation = new CustomerRegisterRelation();
                        $CustomerRegisterRelation->site_id = $site_id;
                        $CustomerRegisterRelation->customer_id = $customer->id;
                        $CustomerRegisterRelation->mode = 1;
                        $CustomerRegisterRelation->created_at = time();
                        $CustomerRegisterRelation->save(false);
                    }
                    $account = CustomerBranchaccount::find()->where(['site_id' => $site_id, 'customer_id' => $customer->id])->one();
                    if ($account == null) {
                        $customer_branchaccount = new CustomerBranchaccount();
                        $customer_branchaccount->customer_id = $customer->id;
                        $customer_branchaccount->site_id = $site_id;
                        $customer_branchaccount->pay_password = md5('123456');
                        $customer_branchaccount->created_at = time();
                        $customer_branchaccount->save(false);
                    }
                    return $this->redirectMessage('添加成功', Fun::url(['customer/details', 'id' => $customer->id]));
                }
            } else {
                $model->site_id = Fun::getSiteId();
                if (isset(\Yii::$app->user->identity) && \Yii::$app->user->identity->role == 'mechanic') {
                    $model->mechanic_id = \Yii::$app->user->identity->mechanic_id;
                }
                if ($model->save(false)) {
                    $CustomerRegisterRelation = new CustomerRegisterRelation();
                    $CustomerRegisterRelation->site_id = $site_id;
                    $CustomerRegisterRelation->customer_id = $model->id;
                    $CustomerRegisterRelation->mode = 1;
                    $CustomerRegisterRelation->created_at = time();
                    $CustomerRegisterRelation->save(false);

                    $customer_branchaccount = new CustomerBranchaccount();
                    $customer_branchaccount->customer_id = $model->id;
                    $customer_branchaccount->site_id = $site_id;
                    $customer_branchaccount->pay_password = md5('123456');
                    $customer_branchaccount->created_at = time();
                    $customer_branchaccount->save(false);
                    return $this->redirectMessage('添加成功', Fun::url(['customer/details', 'id' => $model->id]));
                }
            }

        }
        return $this->render('create', ['form' => $form->render()]);
    }

    public function actionUpdate()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
        }
        $model = Customer::findOne(\Yii::$app->request->get('id'));
        if ($model == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
        }
        $model->scenario = 'update';
        $form = new BuildForm('@app/components/forms/customerupdateForm.php');
        $form->loadModel(['customer' => $model]);
        $now_year = (int)date('Y');
        $oldyear = $now_year - 70;
        $years = range($oldyear, $now_year);
        $arr = [];
        foreach ($years as $y) {
            $arr[$y] = $y;
        }
        $form->setItems('customer', 'age', $arr);
        if ($form->loadData(\Yii::$app->request->post()) && $form->validate()) {
            if ($model->save(false)) {
                return $this->redirectMessage(\Yii::t('zhtfrontend', '信息修改成功'), Fun::url(['customer/details', 'id' => $model->id]));
            }
        }
        return $this->render('create', ['form' => $form->render()]);
    }

    public function actions()
    {
        return [
            'delete' => [
                'class' => DeleteAction::className(),
                'modelClass' => Customer::className(),
                'message' => ['success' => \Yii::t('zhtfrontend', '删除成功')],
                'redirectTo' => 'customer/index',
            ],
            'sendsysessage' => [//发送成功验证码
                'class' => ProceduresAction::className(),
                'behaviorsData' => [
                    [
                        'class' => MsgBehavior::className(),
                    ]
                ],
            ],
            /**'generatesmscode' =>[//生成手机验证码
             * 'class' => 'doumiaoduo\telecaptcha\TelecaptchaAction',
             * 'behaviorsData'=>[
             * [
             * 'class'=>MessageBehavior::className(),
             * ]
             * ]
             * ],*/
        ];
    }


    public function actionDetails()
    {
        $id = \Yii::$app->request->get('id');
        $back_url = Fun::url(['customer/index']);
        if (\Yii::$app->user->identity->role == 'cashier') {
            $this->layout = '@app/views/layouts/iframe2.php';
//            $id = base64_decode($id);
            $back_url = Fun::url(['customer/query']);

        }
        $data = Customer::find()->where(['id' => $id]);
        if (isset(\Yii::$app->user->identity) && \Yii::$app->user->identity->role == 'mechanic') {
            $data->andWhere(['mechanic_id' => \Yii::$app->user->identity->mechanic_id]);
        }
        $model = $data->one();
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $student = Student::find()->where(['customer_id' => $id])->one(); //学生信息
        if (!empty($student) && strlen($student->name) > 30) {
            $student_name = substr($student->name, 0, 30);
            $student->name = $student_name . "...";
        }

        $BAccout = CustomerBranchaccount::find()->where(['customer_id' => $model->id, 'site_id' => Fun::getSiteId()])->one();
        //获取预约订单
        $orders = $this->getOrders(['order_type' => 'appointment', 'customer_id' => $id]); //预约订单
        $orders_data = [];
        foreach ($orders as $k => $v) {
            $orders_item = OrdersItems::find()->where(['orders_id' => $v->id, 'teach_type' => 1])->one();
            $goods_class_time = GoodsClassTime::find()->where(['goods_id' => $orders_item->goods_id])->all();
            foreach ($goods_class_time as $tk => $tv) {
                $class_time[$tk] = Fun::getClassTimes($tv->start_time, $tv->end_time, $tv->class_day);
            }
            $orders_data[$k] = [
                'sn' => $v->sn,
                'telephone' => $v->telephone,
                'total_amount' => $v->total_amount,
                'created_at' => $v->created_at,
                'pay_status' => $v->pay_status,
                'associate_id' => $v->associate_id,
                'goods_name' => $orders_item->goods->name,
                'class_time' => $class_time,
                'status' => $v->status,
                'id' => $v->id,
            ];
        }
        $goodsOrders = $this->getOrders(['order_type' => 'goods', 'customer_id' => $id]); //消费实物订单

        $grade = Customergrade::find()->all();
        $grades = [];
        if ($grade != null) {
            foreach ($grade as $g) {
                $grades[$g->id] = $g->name;
            }
        }
        //获取该会员的预约课程
        // $appointmentItems = $this->getOrderItem(['order_type'=>'appointment','customer_id'=>\Yii::$app->request->get('id')]);
        //获取该会员的消费课程
        // $normalItems = $this->getOrderItem(['order_type'=>'normal','customer_id'=>\Yii::$app->request->get('id')]);
        //转化订单
//        $conversionItems = $this->getOrders(['order_type' => 'conversion', 'customer_id' => $id]);
        //续费订单
        // $renewItems = $this->getOrderItem(['order_type'=>'renew','customer_id'=>\Yii::$app->request->get('id')]);


        return $this->render('details', ['model' => $model, 'student' => $student, 'orders' => $orders_data, 'goodsOrders' => $goodsOrders, 'BAccout' => $BAccout, 'grades' => $grades, 'backUrl' => $back_url]);
    }

    public function actionConformcourse()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $order_id = \Yii::$app->request->get('order_id');
        $orders = Orders::findOne($order_id);
        $student = Student::find()->where(['customer_id' => $orders->customer_id])->one();
        $orders->IDcard = $student->IDcard;
        $orders->scenario = 'conformcourse';
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $orders->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($orders);
        }
        if ($orders->load(\Yii::$app->request->post()) && $orders->validate()) {
            $orders->status = 1;
            $customer_id = $orders->customer_id;
            $student->IDcard = $orders->IDcard;
            $student->save(false);
            if ($orders->save(false)) {
                $option = [
                    'orders_id' => $orders->id,
                    'status' => 1,
                    'result' => 'SUCCESS',
                    'log_text' => '确认订单'
                ];
                Oper::addOrderLog($option);
                return $this->redirectMessage(\Yii::t('zhtfrontend', '课程确认成功'), Fun::url(['customer/details', 'id' => $customer_id]));
            } else {
                return $this->redirectMessage(\Yii::t('zhtfrontend', '课程确认失败'), Fun::url(['customer/details', 'id' => $customer_id]));
            }
        }
        return $this->render('confirm', ['model' => $orders]);

    }


    public function getOrders($param)
    {
        $orders = Orders::find()->where(['customer_id' => $param['customer_id']]);
        if ($param['order_type'] == 'goods') {
            $orders->andWhere(['order_type' => $param['order_type']]);
        } else {
            $orders->andWhere(['!=', 'order_type', 'goods']);
        }
        if (\Yii::$app->user->identity->role === 'cashier') {
            $orders->andWhere(['status' => 1]);
        }
        $orders = $orders->all();
//        print_r($orders);die;
        return $orders;
    }


    public function getOrderItem($param, $type = 1)
    {
        $mids = Fun::getMechanicIds();
        $orders_ids = Orders::find()->select('id')->where(['order_type' => $param['order_type'], 'customer_id' => $param['customer_id']])->andWhere(['>', 'pay_status', 0])->column();
        $ordertype_ids = OrdersType::find()->select('id')->where(['orders_id' => $orders_ids, 'type_id' => 1])->column();
        $itemsModel = OrdersItems::find()->where(['orders_type_id' => $ordertype_ids]);
        if (!empty($mids)) {
            $itemsModel->andWhere(['mechanic_id' => $mids]);
        }
        $orderitems = $itemsModel->all();
        if ($type == 2) {
            $orderitems = Fun::asArray($orderitems, ['status_name', 'created_at', 'avatar']);
        } else {
            $orderitems = Fun::asArray($orderitems, ['status_name', 'check_number', 'created_at', 'student_name', 'class_status']);
            foreach ($orderitems as $key => $item) {
                $orderitems[$key]['goods_attr'] = Funs::getGoodsAttr($item['goods_id']);
                $GoodsTeacher = GoodsAttr::find()->where(['goods_id' => $item['goods_id'], 'obj_type' => 'teacher'])->one();
                $avatar = '';
                if ($GoodsTeacher != null) {
                    $Teacher = Teacher::findOne($GoodsTeacher->attribute_id);
                    if ($Teacher != null) {
                        $avatar = $Teacher->img;
                    }
                }
                $orderitems[$key]['avatar'] = !empty($avatar) ? $avatar : 'images/images/noperson.png';
                $orderitems[$key]['is_deposit'] = 0;
                if (Fun::getSiteMode() == 'A') {
                    $deposit = DepositLog::find()->where(['status' => 0, 'customer_id' => $param['customer_id']])->one();
                    if ($deposit != null) {
                        $orderitems[$key]['is_deposit'] = 1;
                    }
                } else {
                    $deposit = DepositLog::find()->where(['orders_items_id' => $item['id'], 'status' => 0, 'customer_id' => $param['customer_id']])->one();
                    if ($deposit != null) {
                        $orderitems[$key]['is_deposit'] = 1;
                    }
                }
            }
            return $orderitems;
        }
    }

    public function actionOrderitem()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $order_id = \Yii::$app->request->get('order_id');

        $model = Orders::findOne($order_id);
        $datas = [];
        $lesson = [];
        $proItems = [];
        if ($model->order_type == 'goods') {
            $items = OrdersItems::find()->where(['orders_id' => $order_id,])->all();
            foreach ($items as $item) {
                $row['name'] = $item['name'];
                $row['price'] = $item['price'];
                $row['nums'] = $item['nums'];
                $row['amount'] = $item['amount'];

                $proItems[] = $row;
            }
        } else {
            $items = OrdersItems::find()->where(['orders_id' => $order_id, 'teach_type' => 1])->all();
            $row = [];
            foreach ($items as $item) {
                $attr = Funs::getGoodsAttr($item->goods_id);
                $lesson = isset($attr['class_count']) ? $attr['class_count'] : 0;
                $Relation = OrdersItemsRelation::find()->where(['orders_items_id' => $item->id])->one();
                if ($Relation != null) {
                    $lesson = $Relation->lesson;
                }
                $teacher = '';
                $teacherList = GoodsTeacher::find()->select('teacher_name')->where(['goods_id' => $item->goods_id])->column();
                if (!empty($teacherList)) {
                    $teacher = implode(',', $teacherList);
                }
                $classGoods = ClassManageGoods::find()->where(['goods_id' => $item->goods_id])->one();
                $classmanage = ClassManage::find()->where(['class_id' => $classGoods->class_id, 'is_old' => 0, 'type' => 1])->one();

                $have_class_count = 0;
                $status = '未开课';
                $classStudent = ClassStudent::find()->where(['class_manage_id' => $classmanage->class_id, 'student_id' => $item->student_id, 'order_sales_id' => $item->id])->one();
                if ($classStudent != null && $classStudent->status > 0) {
                    switch ($classStudent->status) {
                        case 1:
                            $status = '已开课';
                            break;
                        case 2:
                            $status = '已结课';
                            break;
                        default:
                            $status = '未开课';
                    }
                    $have_class_count = StudentCheck::find()->where(['status' => 1, 'class_student_id' => $classStudent->id])->count();
                }

                $goodsTime = GoodsClassTime::find()->where(['goods_id' => $item->goods_id])->all();
                $tims = '';
                if ($goodsTime) {
                    foreach ($goodsTime as $time) {
                        $tims .= Util::getWeek($time->class_day) . ' ' . $time->start_time . '-' . $time->end_time;
                    }
                }
                $row['coures_name'] = $item->name;
                $row['class_count'] = $lesson;
                $row['max_number'] = isset($attr['max_number']) ? $attr['max_number'] : 0;
                $row['teacher'] = $teacher;
                $row['classroom_name'] = isset($attr['classroom_name']) ? $attr['classroom_name'] : '';
                $row['status'] = $status;
                $row['have_class_count'] = $have_class_count;
                $row['goodstime'] = $tims;

                $proItems[] = $row;
            }


            //获取艺教学
            $art = OrdersItems::find()->where(['orders_id' => $order_id, 'teach_type' => 2])->asArray()->one();
            $datas = [];
            $data = [];
            $lesson = [];
            if (!empty($art)) {
                $classmanage = ClassManage::find()->where(['associate_id' => $art['goods_id'], 'is_old' => 0, 'type' => 2])->one();
                $lesson = ClassLesson::find()->where(['class_id' => $classmanage->class_id])->indexBy('product_id')->asArray()->all();
                switch ($classmanage->status) {
                    case 1:
                        $status = '已开课';
                        break;
                    case 2:
                        $status = '已结课';
                        break;
                    default:
                        $status = '未开课';
                }
                $datas = ArtTeaching::find()->where(['id' => $art['goods_id']])->asArray()->one();
                $datas['have_class_count'] = ClassLesson::find()->where(['>', 'class_date', time()])->andWhere(['class_id' => $classmanage->class_id])->count();
                $datas['status'] = $status;
                $datas['class_time'] = Util::getWeek($datas['class_day']) . ' ' . $datas['star_time'] . '-' . $datas['end_time'];
                $arrangement = (new \yii\db\Query())->select(['ar.*', 'a.*', 'a.id as arrangement_id'])
                    ->from('{{%art_relation}} ar')
                    ->leftJoin('{{%arrangement}} a', 'a.id = ar.arrangement_id')
                    ->where(['ar.art_teaching_id' => $art['goods_id']])
                    ->orderBy('ar.lesson ASC')
                    ->all(Fun::getSiteDb());
                foreach ($arrangement as $item) {
                    $teacher = Teacher::findOne($item['teacher_id']);
                    $coures = Course::findOne($item['course_id']);
                    $classroom = Classroom::findOne($item['classroom_id']);
                    $row['coures_name'] = isset($coures) ? $coures->name : '';
                    $row['teacher_name'] = isset($teacher) ? $teacher->name : '';
                    $row['classroom_name'] = isset($classroom) ? $classroom->name : '';
                    $row['arrangement_id'] = $item['arrangement_id'];
                    $row['lesson'] = $item['lesson'];
                    $row['class_time'] = Util::getWeek($datas['class_day']) . ' ' . $datas['star_time'] . '-' . $datas['end_time'];
                    $data[] = $row;
                }
                $datas['art_list'] = $data;
            }
        }
        //print_r($datas);die;

        return $this->render('orderitem', ['model' => $model, 'couresItems' => $proItems, 'artModel' => $datas, 'lesson' => $lesson]);

    }

    public function actionPay()
    {
        if (\Yii::$app->user->identity->role == 'cashier') {
            $this->layout = '@app/views/layouts/iframe2.php';
        }
        $order_id = \Yii::$app->request->get('order_id');
        $model = Orders::findOne($order_id);
        if ($model->pay_status == 1) {
            return $this->redirectMessage('此订单已支付！', Fun::url(['customer/details', 'id' => $model->customer_id]));
        }
        //检测待支付订单中，是否含有教室不可用课程
//        if(Checkclassroom::Checkclassroom($order_id) == 0){
//            return $this->redirectMessage('此订单含有教室被占用的课程！', Fun::url(['customer/details', 'id' => \Yii::$app->request->get('id')]));
//        }
        $item = OrdersItems::find()->where(['orders_id' => $order_id, 'teach_type' => 1])->one();
        $itemRelation = OrdersItemsRelation::find()->where(['orders_id' => $order_id])->one();
        if ($itemRelation == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }


//        $classGoods = ClassManageGoods::find()->where(['class_id'=>$item->goods_id])->one(); //根据商品id找到班级
//        $classAttr = ClassManageAttribute::find()->where(['class_id'=>$classGoods->class_id])->one();//班级属性
//        if($classAttr->room_type == 1){
//            $classroomIds = Classroom::find()->select('id')->where(['classroom_group_id'=>$classAttr->room_group_id,'state'=>1])->column(); //组里面所有教室
//            $classIds = ClassManageAttribute::find()->select('class_id')->where(['room_group_id'=>$classAttr->room_group_id])->one(); //
//            //ClassManageGoods::find()->select('goods_id')->where(['class_id'=>$classIds])->column();
//
//
//
//
//        }

        $priceRow = GoodsPrice::findOne($itemRelation->goods_price_id);
//        if($priceRow != null) {
//            //if($priceRow->is_activity == 1){
//                $now = time();
//                if($now < $priceRow->activity_start_time || $now > $priceRow->activity_end_time || $priceRow->effective_number == 0){
//                    return $this->redirectMessage('次活动已结束！', Fun::url(['customer/details', 'id' => \Yii::$app->request->get('id')]));
//                }
//           // }
//        }

        $available_scholarship = 0;
        if ($itemRelation != null) {
            if ($itemRelation->is_scholarship == 1) {
                $available_scholarship += $itemRelation->scholarship;
            }
        }
        $account = CustomerBranchaccount::find()->where(['customer_id' => $model->customer_id, 'site_id' => Fun::getSiteId()])->one(); //获取奖学金余额
        if ($account != null) {
            if ($account->scholarship_available >= $available_scholarship) {
                $available_scholarship = $available_scholarship;
            } else {
                $available_scholarship = $account->scholarship_available;
            }
        } else {
            $available_scholarship = 0;
        }
        $goods = Goods::findOne($item->goods_id);
        $deposit = $goods->deposit;

        $AccountRecord = new AccountRecord();
        $AccountRecord->customer_id = $model->customer_id;
        $AccountRecord->scenario = 'orders';
        $customer_coupons = CustomerCoupons::find()->select(['dmd_coupons.name', 'dmd_coupons.total', 'dmd_coupons.total', 'dmd_coupons.type', 'dmd_customer_coupons.*'])->joinWith('coupons')->where(['customer_id' => $model->customer_id, 'use_status' => 0])->andWhere(['>', 'invalid_time', time()])->asArray()->all();
        $coupons = [];
        if ($customer_coupons) {
            foreach ($customer_coupons as $coupon) {
                if ($coupon['total'] <= $model->final_amount && $coupon['type'] != 'freight') {
                    $row['id'] = $coupon['id'];
                    $row['name'] = $coupon['name'];
                    $coupons[] = $row;
                }
            }
        }

        //查询可以转保证金
        $orderItemIds = DepositLog::find()->select('orders_items_id')->where(['customer_id' => $model->customer_id, 'site_id' => Fun::getSiteId(), 'status' => 0, 'processing_status' => 0])->column();
        $endItemIds = ClassStudent::find()->select('order_sales_id')->where(['status' => [2, 4], 'order_sales_id' => $orderItemIds])->all();
        $availableDeposit = DepositLog::find()->where(['orders_items_id' => $endItemIds, 'status' => 0, 'processing_status' => 0, 'site_id' => Fun::getSiteId()])->all();


        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $AccountRecord->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($AccountRecord);
        }

        if ($AccountRecord->load(\Yii::$app->request->post()) && $AccountRecord->validate()) {

            $total_amount = (float)$model->total_amount;
            $final_amount = (float)$model->final_amount;
            $cash_money = $total_amount;
            $post = \Yii::$app->request->post();
            $discount = isset($post['discount']) ? (int)$post['discount'] : 0;
            $discount_type = isset($post['discount_type']) ? $post['discount_type'] : '';
            $customer_id = isset($post['customer_id']) ? (int)$post['customer_id'] : 0;
            $deposit_id = isset($post['deposit']) ? (int)$post['deposit'] : 0;
            $user_id = $customer_id;
            if ((int)$AccountRecord->cash > 0) {
                $money = (int)$AccountRecord->pay_cash + (int)$AccountRecord->pay_wxpay + (int)$AccountRecord->pay_alipay + (int)$AccountRecord->pay_card;
                $AccountRecord->state = 1;
                $AccountRecord->user_id = \Yii::$app->user->id;
                $AccountRecord->site_id = Fun::getSiteId();
                $AccountRecord->cash = $money;
                $AccountRecord->customer_id = $model->customer_id;
                $AccountRecord->note = '充值';
                if ($AccountRecord->save(false)) {
                    $account->cash += $AccountRecord->cash;
                    $account->save(false);
                }
                Account::addRecharge($model->customer_id, $money);
            }

            $item = OrdersItems::find()->where(['orders_id' => $order_id, 'teach_type' => 1])->one();
            $goods = Goods::findOne($item->goods_id);
            $goods_deposit = $goods->deposit;
            $scholarship_money = 0;
            $deposit = 0;
            $paymethod = [];
            if ($discount_type == 'scholarship') {
                $scholarship = $available_scholarship;
                if ($scholarship > $total_amount) {
                    $scholarship_money = $total_amount;
                } else {
                    $scholarship_money = $scholarship;
                }
                $cash_money = $total_amount - $scholarship_money;
                if ($cash_money < $goods_deposit) {
                    $deposit = $goods_deposit;
                }
                $final_amount = $total_amount;
                $total_amount = $total_amount - $scholarship_money;
                $paymethod[] = [
                    'pay_code' => 'pay_scholarship',
                    'pay_name' => '奖学金',
                    'amount' => $scholarship_money
                ];
            }
            $discount_amount = 0;
            if ($discount_type == 'coupon') {
                $customer_coupon = CustomerCoupons::findOne($discount);
                $coupons = Coupons::findOne($customer_coupon->coupon_id);
                if ($coupons->type == 'full') {
                    $discount_amount = $coupons->amount;
                } else {
                    $discount_amount = $total_amount - ($total_amount * $coupons->amount / 100);
                }
                $final_amount = $total_amount - $discount_amount;
                $cash_money = $total_amount - $discount_amount;
                $total_amount = $total_amount - $discount_amount;
                $paymethod[] = [
                    'pay_code' => 'pay_coupon',
                    'pay_name' => '券支付',
                    'amount' => $discount_amount
                ];
            }
            $account_moneys = 0;
            $p_cash = (float)$AccountRecord->p_cash;
            $pay_code = '';
            if ($p_cash > 0) {
                if ($goods->category_id == 1) {
                    $pay_code = 'puzzle_cash';
                    $p_name = '益智专用金额';
                }
                if ($goods->category_id == 2) {
                    $pay_code = 'music_cash';
                    $p_name = '音乐专用金额';
                }
                if ($goods->category_id == 3) {
                    $pay_code = 'body_cash';
                    $p_name = '形体专用金额';
                }
                $paymethod[] = [
                    'pay_code' => $pay_code,
                    'pay_name' => $p_name,
                    'amount' => $p_cash
                ];
                $total_amount = $total_amount - $p_cash;
                $account_moneys += $p_cash;
            }
//            die($total_amount.'ffff');
            $account_money = 0;
            $cash = (float)$account->cash;
            if ($total_amount > 0) {
                if ($cash > $total_amount) {
                    $account_moneys += $total_amount;
                    $account_money += $total_amount;
                    $cash = $cash - $total_amount;
                } else {
                    $account_moneys += $cash;
                    $account_money = $cash;
                    $cash = 0;
                }
                $paymethod[] = [
                    'pay_code' => 'pay_account',
                    'pay_name' => '账户余额',
                    'amount' => $account_money
                ];
            }
            $cash_money = 0;
//            if()
            $model->final_amount = $final_amount;
            $model->remain_amount = $final_amount;
            $model->discount_amount = $discount_amount;
            $model->scholarship_money = $scholarship_money;
            $model->cash_money = $account_moneys;
            $model->account_money = $account_moneys;
            $model->pay_status = 1;
            $model->payment_id = 2;
            $model->pay_time = time();
            $customer = Customer::findOne($model->customer_id);
            $model->customer_card = $customer->card_id;
            if ($model->save(false)) {
                $accountModel = new AccountRecord();
                $accountModel->cash = -($account_money + $scholarship_money);
                $accountModel->customer_id = $model->customer_id;
                $accountModel->site_id = Fun::getSiteId();
                $accountModel->user_id = \Yii::$app->user->id;
                $accountModel->pay_account = ($account_money > 0) ? -$account_money : 0;
                $accountModel->pay_scholarship = ($scholarship_money > 0) ? -$scholarship_money : 0;
                $accountModel->state = 5;
                $accountModel->order_id = $model->id;
                $accountModel->note = '预约课程订单扣除余额和奖学金';
                $accountModel->save(false);
                //减少金额与奖学金
                $account->cash -= $account_money;
                if ($pay_code != '') {
                    $account->$pay_code -= $p_cash;
                }
                $account->scholarship_available -= $scholarship_money;
                $account->save(false);

                if (!empty($paymethod)) {
                    foreach ($paymethod as $pay) {
                        $paymethodModel = new OrdersSquarePaymethod();
                        $paymethodModel->orders_id = $model->id;
                        $paymethodModel->pay_code = $pay['pay_code'];
                        $paymethodModel->pay_name = $pay['pay_name'];
                        $paymethodModel->amount = $pay['amount'];
                        $paymethodModel->create_at = time();
                        $paymethodModel->save(false);
                    }
                }
                //插入保证金
                if ($deposit > 0) {
                    Opercustomer::InsertDeposit($model, $goods_deposit, 2, $deposit_id);
                }
                //班级添加学生
                //if (isset($class_manage) && $class_manage['status'] == 0) {
                Operclassmanager::InsertClassStudent($model);
                // }
                //修改订单商品价格
                Operorders::UpdateOrderItem($order_id, $discount_type, $discount);
                //插入统计
                //if ($model->order_type == 'appointment') {
                Operorders::addReservation($model);
                // }

                //添加机构补贴表
                //if ($model->order_type == 'appointment') {
//                MechanicCommission::InsertoMechanicSubsidy($model);
                //}
                //插入订单操作记录
                $option = [
                    'orders_id' => $model->id,
                    'status' => 2,
                    'result' => 'SUCCESS',
                    'log_text' => '订单支付'
                ];
                Oper::addOrderLog($option);
                //优惠券修改状态
                if ($discount_type == 'coupon') {
                    $customer_coupon->use_status = 1;
                    $customer_coupon->use_time = time();
                    $customer_coupon->save(false);
                }
                //发各类消息
                \Yii::$app->runAction('customer/sendsysessage', ['order_id' => $order_id]);
                \Yii::$app->runAction('customer/sendsysessage', ['order_id' => $order_id, 'receiver_type' => 'teache_teacher']);
                \Yii::$app->runAction('customer/sendsysessage', ['order_id' => $order_id, 'receiver_type' => 'customer']);


                //orders_commission表写数据，结算用
//                if($model->account_money != 0) {
//                    Commission::Insertcommsion($order_id,0);
//                    Commission::Insertcommsion($order_id,1);
//                    Commission::Insertcommsion($order_id,2);
//                }
                return $this->redirectMessage('设置支付成功', Fun::url(['customer/details', 'id' => $user_id]));
            } else {
                return $this->redirectMessage('设置支付失败', Fun::url(['customer/details', 'id' => $user_id]));
            }

        }
        return $this->render('pay', ['account' => $account, 'coupons' => $coupons, 'model' => $model, 'goods' => $goods, 'deposit' => $deposit, 'AccountRecord' => $AccountRecord, 'availableDeposit' => $availableDeposit, 'available_scholarship' => $available_scholarship]);

    }

    //查看支付信息
    public function actionPayinfo()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $order_id = \Yii::$app->request->get('order_id');
        $model = Orders::findOne($order_id);
        if ($model == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
        }
        $items = OrdersItems::find()->where(['orders_id' => $order_id])->all();
        $course = '';
        if ($items != null) {
            foreach ($items as $item) {
                $course .= $item->name . '    ';
            }
        }
        $deposit = 0;
        $depModel = DepositLog::find()->where(['site_id' => Fun::getSiteId(), 'orders_id' => $order_id])->one();
        if ($depModel != null) {
            $deposit = $depModel->money;
        }
        $coupoonamount = 0;
        $OcModel = OrdersCouponsHistory::find()->where(['orders_id' => $order_id])->one();
        if ($OcModel != null) {
            $coupoonamount = $OcModel->amount;
        }
        return $this->render('payinfo', ['model' => $model, 'course' => $course, 'deposit' => $deposit, 'coupoonamount' => $coupoonamount]);

    }

    //使用余额支付计算付款金额
    public function actionCash()
    {
        $order_id = (int)\Yii::$app->request->post('order_id');
        $customer_id = (int)\Yii::$app->request->post('customer_id');
        $checked = (int)\Yii::$app->request->post('checked');
        $discount = (int)\Yii::$app->request->post('discount');
        $discount_type = \Yii::$app->request->post('discount_type');
        \Yii::$app->response->format = Response::FORMAT_JSON;
        $model = Orders::findOne($order_id);
        $amount = $model->total_amount;
        $bond = 0;
        $final_amount = '';
        $return = ['status' => 0];
        $item = OrdersItems::find()->where(['orders_id' => $order_id, 'teach_type' => 1])->one();
        $goods = Goods::findOne($item->goods_id);
        $goods_deposit = $goods->deposit;

        if ($discount > 0) {

            if ($discount_type == 'scholarship') {
                $scholarship = CustomerBranchaccount::find()->where(['customer_id' => $customer_id, 'site_id' => Fun::getSiteId()])->one(); //获取奖学金余额
                if ($scholarship != null) {
                    $return['status'] = 1;
                    $return['final_amount'] = '扣除奖学金：' . $amount . '<br>';
                    if ((int)$scholarship->scholarship_available > $amount) {
                        $baozheng_fee = $goods_deposit;
                        if ($checked) {
                            if ($scholarship->cash > $goods_deposit) {
                                $baozheng_fee = 0;
                                $cash = $goods_deposit;
                            } else {
                                $baozheng_fee = $goods_deposit - $scholarship->cash;
                                $cash = $scholarship->cash;
                            }
                            $return['final_amount'] .= ' 扣除余额：' . $cash . '<br>';
                        }
                        $return['final_amount'] .= ' 保证金:' . number_format($goods_deposit, 2) . '<br> 需支付现金：' . number_format(0 + $baozheng_fee, 2);
                        $return['is_bond'] = 1;
                        $return['total'] = $baozheng_fee;
                        return $return;
                    } else {
                        $amount = $amount - $scholarship->scholarship_available;
                        $final_amount = '扣除奖学金：' . $scholarship->scholarship_available . '<br>';
                        if ($amount < $goods_deposit) {
                            $final_amount .= ' 保证金:' . number_format($goods_deposit, 2) . '<br>';
                            $bond = $goods_deposit;
                            $return['is_bond'] = 1;
                        }
                    }
                }
            } else {
                $customer_coupon = CustomerCoupons::findOne($discount);
                $coupons = Coupons::findOne($customer_coupon->coupon_id);
                $return['status'] = 1;
                if ($coupons->type == 'full') {
                    $amount = number_format($amount - $coupons->amount, 2);
                    $d = $coupons->amount;
                } else {
                    $amount = number_format($amount * $coupons->amount / 100, 2);
                    $d = $model->total_amount - ($model->total_amount * $coupons->amount / 100);
                }
                $final_amount = $coupons->name . '优惠：' . number_format($d, 2) . '<br>';
                //die($final_amount);
            }
        }
        if ($checked == 1) {
            $account = CustomerBranchaccount::find()->where(['customer_id' => $customer_id, 'site_id' => Fun::getSiteId()])->one(); //获取奖学金余额
            if ($account != null) {
                $return['status'] = 1;
                if ((float)$account->cash > $amount) {
                    //var_dump($account->cash);die;
                    $baozheng_fee = 0;
                    if ($return['is_bond']) {
                        if ($account->cash - $amount > $goods_deposit) {
                            $baozheng_fee = $goods_deposit;
                            $bond = 0;
                        } else {
                            $baozheng_fee = (float)$account->cash - $amount;
                            $bond = $goods_deposit - $baozheng_fee;
                        }
                    }
                    // var_dump($return['is_bond']);die;
                    $final_amount .= ' 扣除余额：' . number_format($amount + $baozheng_fee, 2) . '<br> 需支付现金：' . number_format(0 + $bond, 2);
                    $final_amount_total = $bond;

                } else {
                    $final_amount .= ' 扣除余额：' . number_format($account->cash, 2) . '<br> 需支付现金：' . number_format($amount - $account->cash + $bond, 2);
                    $final_amount_total = $amount - $account->cash + $bond;
                }
                $return['final_amount'] = $final_amount;
                $return['total'] = $final_amount_total;
            }
        } else {
            $return['status'] = 1;
            $final_amount .= ' 需支付现金：' . number_format($amount + $bond, 2);
            $return['final_amount'] = $final_amount;
            $return['total'] = $amount + $bond;
        }
        return $return;
    }

    //使用优惠券或奖学金支付计算付款金额
    public function actionDiscount()
    {
        $order_id = \Yii::$app->request->post('order_id');
        $customer_id = \Yii::$app->request->post('customer_id');
        $type = \Yii::$app->request->post('type');
        $val = \Yii::$app->request->post('val');
        $cash = \Yii::$app->request->post('cash');
        \Yii::$app->response->format = Response::FORMAT_JSON;
        $model = Orders::findOne($order_id);
        $amount = $model->total_amount;
        $final_amount = '';
        $bond = 0;
        $return = ['status' => 0, 'is_bond' => 0];
        $item = OrdersItems::find()->where(['orders_id' => $order_id, 'teach_type' => 1])->one();
        $itemRelation = OrdersItemsRelation::find()->where(['orders_items_id' => $item->id])->one();
        $available_scholarship = 0;
        if ($itemRelation != null) {
            if ($itemRelation->is_scholarship == 1) {
                $available_scholarship += $itemRelation->scholarship;
            }
//            if($itemRelation->is_art_scholarship == 1){
//                $available_scholarship += $itemRelation->art_scholarship;
//            }
        }
        $account = CustomerBranchaccount::find()->where(['customer_id' => $customer_id, 'site_id' => Fun::getSiteId()])->one(); //获取奖学金余额
        $goods = Goods::findOne($item->goods_id);
        $goods_deposit = $goods->deposit;

        $p_cash = 0;
        $p_name = '';
        if ($goods->category_id == 1) {
            $p_cash = isset($account->puzzle_cash) ? $account->puzzle_cash : 0;
            $p_name = '益智专用金额';
        }
        if ($goods->category_id == 2) {
            $p_cash = isset($account->music_cash) ? $account->music_cash : 0;
            $p_name = '音乐专用金额';
        }
        if ($goods->category_id == 3) {
            $p_cash = isset($account->body_cash) ? $account->body_cash : 0;
            $p_name = '形体专用金额';
        }

        $p_cashs = 0;
        if ($type == 'scholarship') {
            if ($account != null) {
                $cashs = 0;

                $return['status'] = 1;
                $return['final_amount'] = '扣除奖学金：' . $available_scholarship . '<br>';
                if ($account->scholarship_available >= $available_scholarship) { //如果剩余保证金大于可用保证金
                    if ($p_cash > 0) {
                        if ($p_cash > $amount - $available_scholarship) {
                            $p_cashs = $amount - $available_scholarship;
                        } else {
                            $p_cashs = $p_cash;
                        }
                    }
                    if ($amount - $available_scholarship < $goods_deposit) { //如果总价格减去使用保证金的小于保证金哈需要缴纳保证金
                        $baozheng_fee = $goods_deposit;
                        //if($amount - $available_scholarship > 0){  //如果总价格减去使用的保证金大于0 说明还要缴纳余额或找现金

                        //if($amount - $available_scholarship - $p_cashs >= 0){
                        if ($account->cash >= ($amount - $available_scholarship - $p_cashs) + $baozheng_fee) { //如果余额大于等于需缴纳的薪金部分无需交现金
                            $baozheng_fee = 0;
                            $cashs = ($amount - $available_scholarship - $p_cashs) + $goods_deposit;
                        } else {
                            if ($account->cash > 0) {
                                $cashs = $account->cash;
                            }
                            $baozheng_fee = $baozheng_fee + ($amount - $available_scholarship - $p_cashs - $account->cash);

                        }
                        //  }
                        // }
                        $return['is_bond'] = 1;
                        $return['final_amount'] .= ' 保证金:' . number_format($goods_deposit, 2) . '<br>';
                    } else { //如果缴纳的现金部分大于保证金

                        if ($account->cash >= ($amount - $available_scholarship - $p_cashs)) {
                            $baozheng_fee = 0;
                            $cashs = $amount - $available_scholarship - $p_cashs;
                        } else {
                            if ($account->cash > 0) {
                                $cashs = $account->cash;
                            }
                            $baozheng_fee = $amount - $available_scholarship - $p_cashs - $account->cash;
                        }
                        $return['is_bond'] = 0;
                    }
                    if ($p_cashs > 0) {
                        $return['final_amount'] .= ' 扣除' . $p_name . '：' . number_format($goods_deposit, 2) . '<br>';
                    }
                    if ($cashs > 0) {
                        $return['final_amount'] .= ' 扣除余额：' . $cashs . '<br>';
                    }
                    if ($baozheng_fee > 0)
                        $return['final_amount'] .= '需支付现金：' . number_format(0 + $baozheng_fee, 2);
                    $return['total'] = $baozheng_fee;
                    $return['p_cashs'] = $p_cashs;
                    return $return;
                } else { //如果剩余保证金小于可用保证金
                    $amount = $amount - (float)$account->scholarship_available;
                    if ($p_cash > 0) {
                        if ($p_cash > $amount) {
                            $p_cashs = $amount;
                        } else {
                            $p_cashs = $p_cash;

                        }
                    }
                    $amount = $amount - $p_cashs;
                    $final_amount = '';
                    $final_amount .= '扣除奖学金：' . $account->scholarship_available . '<br>';
                    if ($p_cashs > 0) {
                        $final_amount .= ' 扣除' . $p_name . '：' . number_format($p_cashs, 2) . '<br>';
                    }
                    $return['p_cashs'] = $p_cashs;
                    if ($model->total_amount - (float)$account->scholarship_available < $goods_deposit) {
                        $bond = $goods_deposit;
                        $final_amount .= ' 保证金:' . number_format($goods_deposit, 2) . '<br>';
                        $return['is_bond'] = 1;
                    }
                }
            }

        } else {
            $customer_coupon = CustomerCoupons::findOne($val);
            $coupons = Coupons::findOne($customer_coupon->coupon_id);
            $return['status'] = 1;
            if ($coupons->type == 'full') {
                $amount = number_format($amount - $coupons->amount, 2);
                $d = $coupons->amount;
            } else {
                $amount = number_format($amount * $coupons->amount / 100, 2);
                $d = $model->total_amount - ($model->total_amount * $coupons->amount / 100);
            }
            if ($p_cash > 0) {
                if ($p_cash >= $amount) {
                    $p_cashs = $amount;
                } else {
                    $p_cashs = $p_cash;
                }
                $amount = $amount - $p_cashs;
            }
            $return['p_cashs'] = $p_cashs;
            $final_amount = $coupons->name . '优惠：' . number_format($d, 2) . '<br>';
        }
        if ($cash > 0) {
            $account = CustomerBranchaccount::find()->where(['customer_id' => $customer_id, 'site_id' => Fun::getSiteId()])->one(); //获取奖学金余额
            if ($account != null) {
                $return['status'] = 1;
                $final_amount_total = 0;
                if ($amount > 0) {
                    if ((float)$account->cash > $amount) {
                        $baozheng_fee = 0;
                        if ($return['is_bond']) {
                            if ($account->cash - $amount > $goods_deposit) {
                                $baozheng_fee = $goods_deposit;
                                $bond = 0;
                            } else {
                                $baozheng_fee = (float)$account->cash - $amount;
                                $bond = $goods_deposit - $baozheng_fee;
                            }
                        }
                        $final_amount .= ' 扣除余额：' . number_format($amount + $baozheng_fee, 2) . '<br> 需支付现金：' . number_format(0 + $bond, 2);
                        $final_amount_total = $bond;
                    } else {
                        $final_amount .= ' 扣除余额：' . number_format($account->cash, 2) . '<br> 需支付现金：' . number_format($amount - $account->cash + $bond, 2);
                        $final_amount_total = $amount - $account->cash + $bond;
                    }
                }
                $return['final_amount'] = $final_amount;
                $return['total'] = $final_amount_total;
            }
        } else {
            $return['status'] = 1;
            $final_amount .= ' 需支付现金：' . number_format($amount + $bond, 2);
            $return['final_amount'] = $final_amount;
            $return['total'] = $amount + $bond;
        }
        return $return;
    }

    public function actionTurndeposit()
    {
        $order_id = \Yii::$app->request->post('order_id'); //订单id
        $customer_id = \Yii::$app->request->post('customer_id'); //会员id
        $deposit_id = \Yii::$app->request->post('deposit_id'); //被传保证金id
        \Yii::$app->response->format = Response::FORMAT_JSON;
        $model = Orders::findOne($order_id);
        $amount = $model->total_amount;
        $final_amount = '';
        $bond = 0;
        $return = ['status' => 0, 'is_bond' => 0];
        $item = OrdersItems::find()->where(['orders_id' => $order_id, 'teach_type' => 1])->one();
        $itemRelation = OrdersItemsRelation::find()->where(['orders_items_id' => $item->id])->one();
        $available_scholarship = 0;
        if ($itemRelation != null) {
            if ($itemRelation->is_scholarship == 1) {
                $available_scholarship += $itemRelation->scholarship;
            }
            if ($itemRelation->is_art_scholarship == 1) {
                $available_scholarship += $itemRelation->art_scholarship;
            }
        }
        $goods = Goods::findOne($item->goods_id);
        $goods_deposit = $goods->deposit;
        $model = DepositLog::findOne((int)$deposit_id);
        $account = CustomerBranchaccount::find()->where(['customer_id' => $customer_id, 'site_id' => Fun::getSiteId()])->one(); //获取奖学金余额
        if ($account != null) {
            $return['status'] = 1;
            $return['final_amount'] = '扣除奖学金：' . $available_scholarship . '<br>';
            if ($account->scholarship_available >= $available_scholarship) {
                $baozheng_fee = $goods_deposit;
                if ($model->money >= $goods_deposit) {
                    $baozheng_fee = 0;
                    if ($model->money - $goods_deposit > 0) {
                        //退保证金到账户
                    }
                } else {
                    $baozheng_fee = $goods_deposit - $model->money;
                    if ($account->cash > 0) {
                        if ($account->cash >= $baozheng_fee) {
                            $baozheng_fee = 0;
                            $cash = $baozheng_fee;
                            $return['final_amount'] .= ' 扣除余额：' . $baozheng_fee . '<br>';
                        } else {
                            $baozheng_fee = $baozheng_fee - $account->cash;
                            $cash = $account->cash;
                            $return['final_amount'] .= ' 扣除余额：' . $cash . '<br>';
                            $return['final_amount'] .= ' 需支付现金：' . number_format(0 + $baozheng_fee, 2) . '<br>';
                        }

                    } else {
                        $return['final_amount'] .= ' 需支付现金：' . number_format(0 + $baozheng_fee, 2) . '<br>';
                    }
                }
                $return['total'] = $baozheng_fee;
                return $return;
            } else {
                $amount = $amount - (float)$account->scholarship_available;
                $final_amount = '扣除奖学金：' . $account->scholarship_available . '<br>';
                $baozheng_fee = $goods_deposit;
                if ($model->money >= $goods_deposit) {
                    $baozheng_fee = 0;
                    if ($model->money - $goods_deposit > 0) {
                        //退保证金到账户
                    }
                } else {
                    $baozheng_fee = $goods_deposit - $model->money;
                }
                if ($account->cash > 0) {
                    if ($account->cash >= $amount + $baozheng_fee) {
                        $final_amount .= '扣除余额：' . ($amount + $baozheng_fee) . '<br>';
                    } else {
                        $amount = $amount + $baozheng_fee - $account->cash;
                        $final_amount .= '扣除余额：' . $account->cash . '<br>';
                        $final_amount .= '需支付现金：' . $amount . '<br>';
                    }
                } else {
                    $final_amount .= ' 需支付现金：' . number_format($baozheng_fee + $amount, 2) . '<br>';
                }
                $return['final_amount'] = $final_amount;
                $return['total'] = $baozheng_fee + $amount;
                return $return;

            }

        }

    }


    //查看课程暂时用不到
    public function actionCourse()
    {

        $student_id = \Yii::$app->request->get('id');
        if ($student_id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $ClassStudent = ClassStudent::find()->select('class_manage_id')->where(['student_id' => $student_id])->asArray()->column();
        $ClassManage = ClassManage::find()->where(['class_id' => $ClassStudent])->all();
        $class_count = [];
        if ($ClassManage != null) {
            foreach ($ClassManage as $k => $v) {
                if ($v->arrangeCourse->is_end == 1) {
                    $count = ClassStudent::find()->where(['class_manage_id' => $v->class_id])->count();
                    $class_count[$k]['id'] = $v->class_id;
                    $class_count[$k]['status'] = $v->status;
                    $class_count[$k]['start_time'] = $v->start_time;
                    $class_count[$k]['end_time'] = $v->end_time;
                    $class_count[$k]['course_name'] = $v->arrangeCourse->course->name;
                    $class_count[$k]['teacher_name'] = $v->arrangeCourse->teacher->name;
                    $class_count[$k]['classroom_name'] = $v->arrangeCourse->classroom->name;
                    $class_count[$k]['class_time'] = Fun::getClassTime($v->arrangeCourse->start_time, $v->arrangeCourse->end_time, $v->arrangeCourse->class_day);
                    $class_count[$k]['max_number'] = $v->arrangeCourse->max_number;
                    $class_count[$k]['opening_number'] = $v->arrangeCourse->opening_number;
                    $class_count[$k]['COUNT(id)'] = $count;
                }
            }
        }
        return $this->render('coures', ['model' => $class_count, 'student_id' => $student_id]);
    }


    //订单绑定
    public function actionBound()
    {
        if (\Yii::$app->request->get('id') == null || \Yii::$app->request->get('order_id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $ordersales = OrderSales::findOne(['id' => \Yii::$app->request->get('id')]);
        $order = Order::findOne(['id' => \Yii::$app->request->get('order_id')]);
        if ($ordersales == null || $order == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $ordersales->scenario = 'bound';
        $student = Student::find()->where(['customer_id' => $order->customer_id])->andWhere('IDcard!=""')->indexBy('id')->asArray()->all();
        $items = ArrayHelper::map($student, 'id', 'name');
        $form = new EasyuiForm('@app/components/forms/ordersalesForm.php');
        $form->setItems('ordersales', 'student_id', $items);
        $form->loadModel(['ordersales' => $ordersales]);
        if ($form->loadData(\Yii::$app->request->post())) {
            if ($ordersales->save(false)) {
                //class_manage表
                $classmanage = ClassManage::findOne(['code' => $ordersales->arrange_course_id, 'status' => 0]);
                if ($classmanage === null) {
                    $class_manage = new ClassManage();
                    $class_manage->class_code = 'c' . time();
                    $class_manage->code = $ordersales->arrange_course_id;
                    if ($class_manage->save(false)) {
                        //class_student表
                        $class_student = new ClassStudent();
                        $class_student->class_manage_id = $class_manage->class_id;
                        $class_student->order_sales_id = $ordersales->id;
                        $class_student->student_id = $ordersales->student_id;
                        $class_student->save(false);
                    }
                } else {
                    //class_student表
                    $class_student = new ClassStudent();
                    $class_student->class_manage_id = $classmanage->class_id;
                    $class_student->order_sales_id = $ordersales->id;
                    $class_student->student_id = $ordersales->student_id;
                    $class_student->save(false);
                }
                return $this->redirectMessage('绑定成功', Fun::url(['customer/details', 'id' => $order->customer_id]));
            }

        }
        return $this->render('create', ['form' => $form->render(), 'items' => $items]);
    }

    public function actionChange()
    {
        $id = \Yii::$app->request->get('id');
        $this->layout = '@app/views/layouts/iframe.php';
        if ($id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = Customer::findOne($id);
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $defaultPassword = $model->password;
        $model->password = null;
        $model->scenario = 'change';
        $form = new BuildForm('@app/components/forms/customerchangeForm.php');
        $form->loadModel(['customer' => $model]);

        if ($form->loadData(\Yii::$app->request->post()) && $form->validate()) {
            if ($model->password == null && $model->save(false)) {
                $model->password = $defaultPassword;
            } else {
                $model->password = \Yii::$app->security->generatePasswordHash($model->password);
            }
            if ($model->save(false)) {

                return $this->redirectMessage('修改成功', Fun::url(['customer/details', 'id' => \Yii::$app->request->get('id')]));
            }
        }
        return $this->render('create', ['form' => $form->render()]);

    }

    public function actionAddidcard()
    {
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = Student::findOne(\Yii::$app->request->get('id'));
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model->scenario = 'addidcard';
        $form = new EasyuiForm('@app/components/forms/studentidcardForm.php');
        $form->loadModel(['student' => $model]);
        if ($form->loadData(\Yii::$app->request->post()) && $form->validate()) {
            if ($model->save(false)) {
                return $this->redirectMessage('修改成功', Fun::url(['customer/details', 'id' => $model->customer_id]));
            }
        }
        return $this->render('create', ['form' => $form->render()]);
    }

//绑定学员
    public function actionBind()
    {
        $this->layout = '@app/views/layouts/iframe.php';
//        $this->layout = false;
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $id = \Yii::$app->request->get('id');
        $customer = Customer::findOne($id);
        if ($customer == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $student = Student::find()->where(['customer_id' => $customer->id])->one();

        $model = new Student();
        if ($student != null) {
            $model->name = $student->name;
            $model->nickname = $student->nickname;
            $model->sex = $student->sex;
            $model->birthday = $student->birthday;
            $model->IDcard = $student->IDcard;
            $model->img = $student->img;
            $model->blood_type = $student->blood_type;
            $model->school = $student->school;
            $model->hobby = $student->hobby;
            $model->father_phone = $student->father_phone;
            $model->father_company = $student->father_company;
            $model->mother_phone = $student->mother_phone;
            $model->father_company = $student->father_company;
            $model->address = $student->address;
            $model->finish_studying = $student->finish_studying;
            $model->intention_studying = $student->intention_studying;
            $model->source = $student->source;
            $model->company_type = $student->company_type;
            $model->main_contacts = $student->main_contacts;
            $model->main_phone = $student->main_phone;
        }
        $model->scenario = 'addidcard';
        $model->site_id = Fun::getSiteId();
        $form = new BuildForm('@app/components/forms/studentForm.php');
        $form->loadModel(['student' => $model]);
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'student-form' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($form->loadData(\Yii::$app->request->post()) && $form->validate()) {
            $post = \Yii::$app->request->post('Student');
            $model->IDcard = $post['IDcard'];
            if ($student != null) {
                $student->updated_at = time();
                $student->name = $model->name;
                $student->nickname = $model->nickname;
                $student->sex = $model->sex;
                $student->birthday = $model->birthday;
                $student->IDcard = $model->IDcard;
                $student->img = $model->img;
                $student->blood_type = $model->blood_type;
                $student->school = $model->school;
                $student->hobby = $model->hobby;
                $student->father_phone = $model->father_phone;
                $student->father_company = $model->father_company;
                $student->mother_phone = $model->mother_phone;
                $student->mother_company = $model->mother_company;
                $student->address = $model->address;
                $student->finish_studying = $model->finish_studying;
                $student->intention_studying = $model->intention_studying;
                $student->source = $model->source;
                $student->company_type = $model->company_type;
                $student->main_contacts = $model->main_contacts;
                $student->main_phone = $model->main_phone;
                $student->save(false);
            } else {
                $model->customer_id = $customer->id;
                $model->save(false);
            }
//            $customer->age = $model->age;
//            $customer->save(false);

            return $this->redirectMessage('编辑成功', Fun::url(['customer/details', 'id' => \Yii::$app->request->get('id')]));
        } else {
//            print_r($student->getErrors());die;
        }
        return $this->render('create', ['form' => $form->render()]);
    }

    //打印胸牌
    public function actionPrint()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $id = \Yii::$app->request->get('id');
        $customer = Customer::findOne($id);
        if ($customer == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }

        if ($customer->card_id == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '请先开卡！'));
        }

        $model = Student::find()->where(['customer_id' => $customer->id])->one();
        $path = "images/qrcode/";
        if (!file_exists($path)) {
            mkdir($path);
        }
        $filesize = @getimagesize($model->qrcode_url);
        if ($model->qrcode_url == null || !$filesize) {
            $pathFile = 'images/qrcode/' . $customer->card_id . '.png';
            QrCode::png($customer->card_id, $pathFile, 0, 6, 1);
            $model->qrcode_url = $pathFile;
            $model->save(false);
        }
        return $this->render('print', ['model' => $model, 'customer' => $customer]);
    }

    //开卡(开卡的时候根据情况向用户的账户scholarship_available中冲1500或者是2000元)
    public function actionCard()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $id = \Yii::$app->request->get('id');
        $model = Customer::findOne($id);
        $customer_id = \Yii::$app->request->get('id');
        $model->scenario = 'card';
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        if($model->card_id == null || empty($model->card_id)) {
            $cardNumber = (new RequestManage())->getCardNUmber();
            $a = 0;
            do {
                $info = Customer::find()->where(['card_id' => $cardNumber])->one();
                if ($info != null) {
                    $a++;
                }
            } while ($a > 0);
            $model->card_id = (string)$cardNumber;
        }
        $row = CardAttr::find()->where(['customer_id' => $customer_id])->one();
        $form = new BuildForm('@app/components/forms/customercardForm.php');
        $form->loadModel(['customer' => $model]);


        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'customer-form' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }

        if ($form->loadData(\Yii::$app->request->post()) && $form->validate()) {
            $model->card_qrcode = md5($model->card_id);
            if ($model->save(false)) {
                if ($model->pay_password != null) {
                    $account = CustomerBranchaccount::find()->where(['customer_id' => $model->id, 'site_id' => Fun::getSiteId()])->one();
                    $account->pay_password = md5($model->pay_password);
                    $account->save(false);
                }
                return $this->redirectMessage(\Yii::t('zhtfrontend', '开卡成功'), Fun::url(['customer/details', 'id' => \Yii::$app->request->get('id')]));
            }
        }
//        else{
//            print_r($model->getErrors());die;
//        }
        return $this->render('create', ['form' => $form->render(), 'row' => $row, 'model' => $model]);
    }

    public function actionBindcard()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = Customer::findOne($id);
        $model->scenario = 'bindcard';
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            if ($model->save(false)) {
                return $this->redirectMessage(\Yii::t('zhtfrontend', '绑定成功'), Fun::url(['customer/details', 'id' => $id]));
            }
        }
        return $this->render('bindcard', ['model' => $model]);
    }

    public function actionRemarks()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $id = \Yii::$app->request->get('id');
        $model = Customer::findOne($id);
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $form = new BuildForm('@app/components/forms/customerremarksForm.php');
        $form->loadModel(['customer' => $model]);
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'customer-form' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($form->loadData(\Yii::$app->request->post()) && $form->validate()) {
            if ($model->save(false)) {
                return $this->redirectMessage(\Yii::t('zhtfrontend', '备注成功'), Fun::url(['customer/details', 'id' => \Yii::$app->request->get('id')]));
            }
        }
        return $this->render('remarks', ['form' => $form->render(), 'model' => $model]);
    }

    public function actionCharge()
    {
        $this->layout = false;
        $id = \Yii::$app->request->get('id');
        $customer = Customer::findOne($id);
        if ($customer == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '用户不存在'));
        }
        $model = new AccountRecord();
        $model->scenario = 'charge';
        $form = new BuildForm('@app/components/forms/accountrecordchargeForm.php');
        $funllList = FullActivities::find()->where(['status' => 1])->andWhere('number>0')->andWhere(['<=', 'start_time', time()])->andWhere(['>=', 'end_time', time()])->all();
        $arr1[0] = '普通充值';
        foreach ($funllList as $item) {
            $arr1[$item->id] = $item->name . ' ' . date('Y/m/d', $item->start_time) . '-' . date('Y/m/d', $item->end_time);
        }

//        print_r($arr1);die;
        //$arr2 = ArrayHelper::map($funllList,'id','name');
        //$newarr = $arr1+$arr2;
        $form->setData('accountrecord', 'full_activities_id', 'data', $arr1);
//        $form->setItems('accountrecord','full_activities_id',$arr1);
        $form->loadModel(['accountrecord' => $model]);
        $form->loadDefaultValues();
        $site_id = Fun::getSiteId();
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'accountrecord-form' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }

        $BAccout = CustomerBranchaccount::find()->where(['customer_id' => $id, 'site_id' => Fun::getSiteId()])->one();
        if ($form->loadData(\Yii::$app->request->post()) && $form->validate()) {
            $money = (float)$model->pay_cash + (float)$model->pay_card + (float)$model->pay_wxpay + (float)$model->pay_alipay + (float)$model->free;
            $model = $form->getModel('accountrecord');
            $model->site_id = $site_id;
            $model->user_id = \Yii::$app->user->id;
            $model->cash = $money;
            $model->customer_id = $customer->id;
            $model->state = 1;
            $model->note = '充值';
            $full = null;
            if ($model->full_activities_id > 0) {
                $full = FullActivities::findOne($model->full_activities_id);
                $full->number -= 1;
                $full->save(false);
            }
            if ($BAccout == null) {
                $BAccout = new CustomerBranchaccount();
                $BAccout->customer_id = $customer->id;
                $BAccout->site_id = $site_id;
                if ($full == null) {
                    $BAccout->cash = $money;
                } else {
                    if ($full->type == 1) {
                        $BAccout->puzzle_cash = $money;
                    } elseif ($full->type == 2) {
                        $BAccout->music_cash = $money;
                    } else {
                        $BAccout->body_cash = $money;
                    }
                }

                $BAccout->mode = 2;
            } else {
                if ($full == null) {
                    $BAccout->cash += $money;
                } else {
                    if ($full->type == 1) {
                        $BAccout->puzzle_cash += $money;
                    } elseif ($full->type == 2) {
                        $BAccout->music_cash += $money;
                    } else {
                        $BAccout->body_cash += $money;
                    }
                }
            }

            $array = ['pay_cash' => $model->pay_cash, 'pay_wxpay' => $model->pay_wxpay, 'pay_card' => $model->pay_card, 'pay_alipay' => $model->pay_alipay, 'free' => $model->free, 'total' => $model->cash];
            $str = '';
//            $str .= '
//                <table>
//                    <tr>充值小票打印</tr>
//                    <tr><td>现金支付</td><td>' . Html::encode($array['pay_cash']) . '</td></tr>
//                    <tr><td>微信支付</td><td>' . Html::encode($array['pay_wxpay']) . '</td></tr>
//                    <tr><td>支付宝支付</td><td>' . Html::encode($array['pay_alipay']) . '</td></tr>
//                    <tr><td>卡支付</td><td>' . Html::encode($array['pay_card']) . '</td></tr>
//                    <tr><td>免费赠送</td><td>' . Html::encode($array['free']) . '</td></tr>
//                    <tr><td>总计</td><td>' . Html::encode($array['total']) . '</td></tr>
//                </table>';
            if ($model->save(false) && $BAccout->save(false)) {
                Account::addRecharge($customer->id, $money);
                return $this->redirectMessage('添加成功', Fun::url(['customer/details', 'id' => \Yii::$app->request->get('id')]));
            }
        }
        return $this->render('charge', ['form' => $form->render(), 'model' => $model, 'customer' => $customer, 'BAccout' => $BAccout]);
    }

    //消费
    public function actionConsume()
    {
        $url = [];
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $id = \Yii::$app->request->get('id');
        $customer = Customer::findOne($id);
        if ($customer == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $account = CustomerBranchaccount::find()->where(['site_id' => Fun::getSiteId(), 'customer_id' => $customer->id, 'mode' => 2])->one();
        $student = Student::find()->where(['customer_id' => \Yii::$app->request->get('id')])->one();
        if ($student == null) {
            return $this->redirectMessage('请先编辑学员信息', Fun::url(['customer/details', 'id' => $customer->id]), false, [], '', 'error');
        }

        //获取优惠券
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'aa') {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $coupon_cache = Fun::cache('coupon_cache', false);
            $id = \Yii::$app->request->post('coupon_id');
            $ajax_object = new AjaxObject();
            if (isset($coupon_cache[$id])) {
                $ajax_object->data = $coupon_cache[$id];
            }
            return $ajax_object;
        }
        $url['back'] = Fun::url(['customer/details', 'id' => \Yii::$app->request->get('id')]);
        $model = new Orders();
        $model->scenario = 'consume';
        $model->customer_id = $customer->id;
        $model->account = $customer->account;
        $model->password_r = $customer->password;

        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        //order
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $post = \Yii::$app->request->post();
            $goods_id = $post['Orders']['goods_id'];
            $goods = Goods::findOne($goods_id);
            $transaction = \Yii::$app->db->beginTransaction();
            try {
                //插入订单
                $model->sn = date('YmdHis') . rand(1000, 9999);
                $model->remain_amount = $model->final_amount;
                $model->pay_status = 0;
                $model->ship_status = 1;
                $model->payment_id = 2;
                $model->customer_id = $customer->id;
                $model->status = 1;
                $model->item_num = 1;
                $model->ip = (new RequestManage())->getUserIP();
                $model->item_amount = $model->total_amount;
                $model->order_source = 'pc';
                $model->give_points = $goods->score;
                $model->created_at = time();
                $model->order_type = 'normal';
                $model->telephone = $customer->mobile;
                $model->cash_money = $model->final_amount;
                $model->scholarship_money = $customer->card_id;
                $model->customer_card = 0;
                $model->save(false);
                ZhtOper::perfectOrder($model, $goods, $customer);
                //操作用户金额
//                $option = [
//                    'customer_id' =>$customer->id,
//                    'account'     =>$model->final_amount,
//                    'scholarship_available'=>0,
//                    'orders_id'   =>$model->id,
//                    'note'        => '消费订单扣除余额',
//                    'state'       =>5
//                ];
//                if(Account::CustomerAccountReduce($option)){
//                    //修改订单支付状态
//                    $orders = Orders::findOne($model->id);
//                    $orders->pay_status = 1;
//                    $orders->pay_time = time();
//                    $orders->save(false);

                //增加订单记录
                $log = [
                    'orders_id' => $model->id,
                    'status' => 2,
                    'result' => 'SUCCESS',
                    'log_text' => '订单支付'
                ];
                ZhtOper::addOrderLog($log);

//                }
                $transaction->commit();
                return $this->redirectMessage('消费成功', Fun::url(['customer/details', 'id' => \Yii::$app->request->get('id')]));

            } catch (\Exception $e) {
                $transaction->rollBack();
                return $this->redirectMessage('消费失败', Fun::url(['customer/details', 'id' => \Yii::$app->request->get('id')]));
            }
        } else {
            // print_r($model->getErrors());die;
        }
        return $this->render('consume', ['customer' => $customer, 'account' => $account, 'model' => $model, 'url' => $url, 'orderType' => 'normal']);
    }

    public function actionAdd()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $type = \Yii::$app->request->get('orderType');
        $customer_id = \Yii::$app->request->get('customer_id');
        if (\Yii::$app->request->isAjax) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            if (\Yii::$app->request->post('ajax') == 'goodsprice') {
                $return = ['status' => 0, 'content' => '', 'priceList' => [], 'artList' => []];
                $goods_id = \Yii::$app->request->post('id');
                if ($goods_id == null) {
                    $return['content'] = '系统错误刷新页面重试！';
                    return $return;
                }
                $goods = Goods::findOne($goods_id);
                $priceList = GoodsPrice::find()->where(['goods_id' => $goods_id, 'back_status' => 1])->asArray()->all();
                if (empty($priceList)) {
                    $return['content'] = '系统错误刷新页面重试！';
                    return $return;
                }
                $returnArr = [];
                foreach ($priceList as $k => $p) {
                    $scholarship = 0;
                    $scholarship_desc = '不可使用奖学金';
                    $lesson_price = $p['lesson_price'];
                    if ($p['is_scholarship'] == 1) {
                        $scholarship += $p['scholarship'];
                    }
                    if ($scholarship > 0) {
                        $scholarship_desc = '可使用奖学金' . $scholarship . '元';
                    }
                    $lesson = $p['lesson'];
                    if ($p['is_frequency'] == 0) {
                        $lesson = '不限课次';
                    }
//                    if ($p['is_activity'] == 1) {
                    if ($p['effective_number'] > 0 && ($p['activity_start_time'] < time() && $p['activity_end_time'] > time())) {
                        $row = [
                            'id' => $p['id'],
                            'lesson_price' => $lesson_price,
                            'price_name' => $p['price_name'],
                            'lesson' => $lesson,
                            'scholarship_desc' => $scholarship_desc,
                            'activity_name' => '-' . $p['activity_name'],
                        ];
                    } else {
                        $row = [
                            'id' => $p['id'],
                            'lesson_price' => $p['market_price'],
                            'price_name' => $p['price_name'],
                            'lesson' => $lesson,
                            'scholarship_desc' => $scholarship_desc,
                            'activity_name' => '',
                        ];
                    }
                    if (!empty($row))
                        $returnArr[] = $row;
                }
                $return['status'] = 1;
                $return['priceList'] = $returnArr;
                //$return['artList'] = $artList;
                return $return;
            }
            if (\Yii::$app->request->post('param') != null) $param = Json::decode(\Yii::$app->request->post('param'));
            $pageSize = isset($param['pageSize']) ? $param['pageSize'] : 12;

            $where = ['is_shelve' => 1, 'is_delete' => 0, 'type_id' => 1, 'status' => 1];
            if ($type == 'normal') {
                $where['is_buy'] = 1;
            } else {
                $where['is_booking'] = 1;
            }
            $data = Goods::find()->where($where)->andWhere('store>0')->orderBy('id DESC');
            if (!empty($param['searchData'])) {
                $search_data = array_filter($param['searchData']);
                if (!empty($search_data['name'])) {
                    $data->andWhere(['like', 'name', $search_data['name']]);
                }
                if (!empty($search_data['cate_id'])) {
                    $data->andWhere('cate_id=:cate_id', [':cate_id' => $search_data['cate_id']]);
                }
            }
            $mids = Fun::getMechanicIds();
            if (!empty($mids)) {
                $data->andWhere(['mechanic_id' => $mids]);
            }
            $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $pageSize]);
            isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;
            $model = $data->offset($pages->offset)->limit($pages->limit)->all();
            $result = Fun::asArray($model, ['cate_name']);
            foreach ($result as $key => $val) {
                $result[$key]['group_title'] = '无艺教学';
                $group = GoodsGroup::find()->where(['goods_id' => $val['id']])->one();
                if ($group != null) {
                    $artModel = ArtTeaching::findOne($group->group_id);
                    $result[$key]['group_title'] = $artModel->title;
                    $result[$key]['price'] = $group->price;
                }
                $str = '';
                $attr = GoodsAttr::InitParam($val['id']);
                $classday = GoodsClassTime::find()->where(['goods_id' => $val['id']])->all();
                if ($classday) {
                    foreach ($classday as $day) {
                        $str .= Util::getWeek($day->class_day) . $day->start_time . '-' . $day->end_time . ' ';
                    }
                }
                $teacher = isset($attr['teacher']) ? $attr['teacher'] : '';;
                $teacherArr = GoodsTeacher::find()->select('teacher_name')->where(['goods_id' => $val['id']])->column();
                if (!empty($teacherArr)) {
                    $teacher = implode(',', $teacherArr);
                }
                $result[$key]['is_group'] = $val['is_group'] == 1 ? '是' : '否';
                $result[$key]['checkbox'] = Html::radio('checkbox', false, ['value' => $val['id']]);
                $result[$key]['teacher_name'] = $teacher;
                $result[$key]['classroom_name'] = isset($attr['classroom_name']) ? $attr['classroom_name'] : '';
                $result[$key]['class_day'] = $str;
                $result[$key]['class_count'] = isset($attr['class_count']) ? $attr['class_count'] : '';
                $result[$key]['max_number'] = isset($attr['max_number']) ? $attr['max_number'] : '';
                $result[$key]['opening_number'] = isset($attr['opening_number']) ? $attr['opening_number'] : '';
                $result[$key]['room_number'] = isset($attr['classroom_number']) ? $attr['classroom_number'] : '';
            }
            $ajax_object = new AjaxObject();
            $ajax_object->data = $result;
            $ajax_object->pages = $pages;
            return $ajax_object;
        }
        $cate = Category::find()->indexBy('id')->all();
        $new_cate = (new Tree($cate))->get_tree_select();
        return $this->render('add', ['new_cate' => $new_cate]);
    }

    //购买实物商

    public function actionOrder()
    {
        $url = [];
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $id = \Yii::$app->request->get('id');
        $customer = Customer::findOne($id);
        if ($customer == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $student = Student::find()->where(['customer_id' => $id])->one();
        if ($student == null) {
            return $this->redirectMessage('请先编辑学员信息', Fun::url(['customer/details', 'id' => \Yii::$app->request->get('id')]), false, [], '', 'error');
        }

        $account = CustomerBranchaccount::find()->where(['site_id' => Fun::getSiteId(), 'customer_id' => $customer->id, 'mode' => 2])->one();

        //获取优惠券
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'aa') {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $coupon_cache = Fun::cache('coupon_cache', false);
            $id = \Yii::$app->request->post('coupon_id');
            $ajax_object = new AjaxObject();
            if (isset($coupon_cache[$id])) {
                $ajax_object->data = $coupon_cache[$id];
            }
            return $ajax_object;
        }

        $url['back'] = Fun::url(['customer/details', 'id' => \Yii::$app->request->get('id')]);
        $model = new Orders();
        $model->scenario = 'order';
        $model->password_r = $customer->password;
        $model->customer_id = $customer->id;
        $model->art_id = 0;

        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        //order
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $post = \Yii::$app->request->post();
            $goods_id = (int)$post['Orders']['goods_id'];
            //$art_id = (int)$post['Orders']['art_id'];
            $price_id = (int)$post['Orders']['goods_price_id'];
            $points = 0;

            $goods = Goods::findOne($goods_id);

            $Goodsprice = GoodsPrice::findOne($price_id);
            $order_type = 'consume';
            $scholarship_available = 0;
            $cash_money = $model->final_amount;
            if ($Goodsprice->is_scholarship == 1) {
                $order_type = 'appointment';
                $scholarship_available += $Goodsprice->scholarship;
            }
//            if($Goodsprice->is_art_scholarship == 1 && $goods->is_group == 1){
//                $scholarship_available += $Goodsprice->art_scholarship;
//            }
            $scholarship_availables = 0;
            if (!empty($account->scholarship_available) && $scholarship_available > 0) {
                if ($account->scholarship_available >= $scholarship_available) {
                    $scholarship_availables = $scholarship_available;
                    $cash_money = $model->final_amount - $scholarship_available;
                } else {
                    $scholarship_availables = $account->scholarship_available;
                    $cash_money = $model->final_amount - $scholarship_available;
                }
            }

            $transaction = \Yii::$app->db->beginTransaction();
            try {
                //插入订单
                $model->sn = date('YmdHis') . rand(1000, 9999);
                $model->remain_amount = $model->final_amount;
                $model->pay_status = 0;
                $model->ship_status = 1;
                $model->payment_id = 2;
                $model->status = 1;
                $model->item_num = 2;
                $model->ip = (new RequestManage())->getUserIP();
                $model->item_amount = $model->total_amount;
                $model->order_source = 'background';
                $model->give_points = $goods->score;
                $model->created_at = time();
                $model->order_type = $order_type;
                $model->telephone = $customer->mobile;
                $model->cash_money = $cash_money;
                $model->scholarship_money = $scholarship_availables;
                $model->customer_card = $customer->card_id;
                $model->mechanic_id = $goods->mechanic_id;
                $model->type_id = isset($goods->cate->type_id) ? $goods->cate->type_id : 1;
                $model->save(false);
                ZhtOper::perfectOrder($model, $goods, $customer, $price_id);
                //增加订单记录
                $log = [
                    'orders_id' => $model->id,
                    'status' => 0,
                    'result' => 'SUCCESS',
                    'log_text' => '管理员下单'
                ];
                ZhtOper::addOrderLog($log);


                //操作用户金额


//                $option = [
//                    'customer_id' =>$customer->id,
//                    'account'     =>$cash_money,
//                    'scholarship_available' => $scholarship_available,
//                    'orders_id'   =>$model->id,
//                    'note'        => '预约课程订单扣除余额',
//                    'state'       =>5,
//                    'mode'        =>2, //综合体下消费
//                ];
//                if(Account::CustomerAccountReduce($option)){
//                    //修改订单支付状态
//                    $orders = Orders::findOne($model->id);
//                    $orders->pay_status = 1;
//                    $orders->pay_time = time();
//                    $orders->save(false);
//
//                    //增加订单记录
//                    $log = [
//                        'orders_id'=>$model->id,
//                        'status'   => 2,
//                        'result'   =>'SUCCESS',
//                        'log_text' => '订单支付'
//                    ];
//                    ZhtOper::addOrderLog($log);
//
//                }
                $transaction->commit();
                return $this->redirectMessage('预约成功', Fun::url(['customer/details', 'id' => \Yii::$app->request->get('id')]));

            } catch (\Exception $e) {
                $transaction->rollBack();
                return $this->redirectMessage('预约失败', Fun::url(['customer/details', 'id' => \Yii::$app->request->get('id')]));
            }
        }
        return $this->render('consume', ['customer' => $customer, 'account' => $account, 'model' => $model, 'url' => $url, 'orderType' => 'appointment']);
    }

    public function actionAddcourse()
    {
        if (\Yii::$app->request->isAjax) {
            if (\Yii::$app->request->post('param') != null) $param = Json::decode(\Yii::$app->request->post('param'));
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $pageSize = isset($param['pageSize']) ? $param['pageSize'] : 12;
            //排序方式不可更改
            $data = Sales::find()->orderBy('id ASC')->where(['in', 'status', [3, 4]])->andWhere(['type' => 0, 'is_book' => 1])->andWhere('total_stock>0');
            if (!empty($param['searchData'])) {
                $search_data = array_filter($param['searchData']);
                if (!empty($search_data['category_id'])) {
                    $data->andWhere('category_id=:category_id', [':category_id' => $search_data['category_id']]);
                }
                if (!empty($search_data['title'])) {
                    $data->andWhere(['like', 'title', $search_data['title']])->andWhere(['type' => 0]);
                }
            }
            $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $pageSize]);
            isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;
            $model = $data->offset($pages->offset)->limit($pages->limit)->all();
            $ajax_object = new AjaxObject();
            $ajax_object->data = Fun::asArray($model, ['category_name', 'class_day', 'start_time', 'end_time', 'max_number', 'opening_number', 'price', 'course_name', 'teacher_name', 'room_number', 'mechanic_name']);
            $ajax_object->pages = $pages;
            return $ajax_object;
        }
        $category_id = \Yii::$app->request->get('category_id');
        return $this->render('addcourse', ['category_id' => $category_id]);
    }

    //转化/续费选择课程
    public function actionTransformcourse()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        $goods = Goods::findOne($id);
        if (\Yii::$app->request->isAjax) {
            if (\Yii::$app->request->post('param') != null) $param = Json::decode(\Yii::$app->request->post('param'));
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $pageSize = isset($param['pageSize']) ? $param['pageSize'] : 12;
            $data = Goods::find()->orderBy('id ASC')->where(['cat_id' => $goods->cat_id, 'mechanic_id' => $goods->mechanic_id, 'goods_type' => 'normal', 'is_shelve' => 1, 'is_delete' => 0])->andWhere(['>', 'store', 0])->andWhere(['<>', 'id', $id]);
            if (!empty($param['searchData'])) {
                $search_data = array_filter($param['searchData']);
                if (!empty($search_data['name'])) {
                    $data->andWhere(['like', 'name', $search_data['name']]);
                }
            }
            $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $pageSize]);
            isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;
            $model = $data->offset($pages->offset)->limit($pages->limit)->all();
            $result = Fun::asArray($model, ['cate_name']);
            foreach ($result as $key => $val) {
                $attr = GoodsAttr::InitParam($val['id']);
                $str = '';
                $classday = GoodsClassTime::find()->where(['goods_id' => $val['id']])->all();
                if ($classday) {
                    foreach ($classday as $day) {
                        $str .= Util::getWeek($day->class_day) . $day->start_time . '-' . $day->end_time . ' ';
                    }
                }
                $result[$key]['checkbox'] = Html::checkbox('checkbox', false, ['value' => $val['id']]);
                $result[$key]['teacher_name'] = isset($attr['teacher']) ? $attr['teacher'] : '';
                $result[$key]['room_number'] = isset($attr['classroom']) ? $attr['classroom'] : '';
                $result[$key]['class_day'] = $str;
                $result[$key]['class_count'] = isset($attr['class_count']) ? $attr['class_count'] : '';
                $result[$key]['max_number'] = isset($attr['max_number']) ? $attr['max_number'] : '';
                $result[$key]['opening_number'] = isset($attr['opening_number']) ? $attr['opening_number'] : '';
                $result[$key]['room_number'] = isset($attr['classroom_number']) ? $attr['classroom_number'] : '';
            }
            //print_r($result);die;
            $ajax_object = new AjaxObject();
            $ajax_object->data = $result;
            $ajax_object->pages = $pages;
            return $ajax_object;
        }
        $cate = Category::find()->indexBy('id')->all();
        $new_cate = (new Tree($cate))->get_tree_select();
        return $this->render('transformcourse', ['new_cate' => $new_cate]);
    }

    //转化
    public function actionTransform()
    {

        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $order_id = \Yii::$app->request->get('id');
        $orders = Orders::findOne(\Yii::$app->request->get('id'));
        if ($orders == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $order_type = \Yii::$app->request->get('order_type');
        if ($order_type == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '系统错误！'));
        }
        $orderItem = OrdersItems::find()->where(['orders_id' => $order_id, 'teach_type' => 1])->one();

        $goods = Goods::findOne($orderItem->goods_id);
        $attr = Fun::getGoodsAttr($orderItem->goods_id); //课程的属性
        $class_count = (int)$attr['class_count']; //预约的课次
        $goods_price = $goods->price;
        if ($goods->discount_type == 1) {
            $goods_price = $goods->price - ($goods->price * $goods->reduce / 100);
        }
        if ($goods->discount_type == 2) {
            $goods_price = $goods->price - $goods->reduce;
        }
        $lesson_price = round($goods_price / $class_count); //单课次价格
        //上课时间
        $classTime = GoodsClassTime::find()->where(['goods_id' => $orderItem->goods_id])->all();
        $str = '';
        if ($classTime != null) {
            foreach ($classTime as $time) {
                $str .= Util::getWeek($time->class_day) . $time->start_time . '-' . $time->end_time;
            }
        }
        $group = GoodsGroup::find()->where(['goods_id' => $orderItem->goods_id])->one();
        $artModel = null;
        $artModelLesson = [];
        $art_lesson_price = 0;
        if ($group != null) {
            $artModel = ArtTeaching::findOne($group->group_id);
            $art_price = $artModel->price;
            if ($group->discount_type == 1) {
                $art_price = $artModel->price - ($artModel->price * $group->price_reduce / 100);
            }
            if ($group->discount_type == 2) {
                $art_price = $artModel->price - $group->price_reduce;
            }
            $artModel->price = $art_price;
            $art_lesson_price = round($artModel->price / $artModel->class_count);
            $artModelLesson[$artModel->class_count] = $artModel->class_count;
            $artModelLesson[2 * $artModel->class_count] = 2 * $artModel->class_count;
            $artModelLesson[3 * $artModel->class_count] = 3 * $artModel->class_count;
            $artModelLesson[4 * $artModel->class_count] = 4 * $artModel->class_count;
            $artModelLesson[5 * $artModel->class_count] = 5 * $artModel->class_count;
        }
        $customer = Customer::findOne(['id' => $orders->customer_id]);
        if ($customer == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $account = 0;
        $Branchaccount = CustomerBranchaccount::find()->where(['customer_id' => $orders->customer_id, 'site_id' => Fun::getSiteId()])->one();
        if ($Branchaccount != null) {
            $account = $Branchaccount->cash;
        }
        $model = new Orders();
        $model->scenario = 'transform';
        $model->password_r = $customer->password;
        $model->account = $customer->account;
        $model->goods_id = $orderItem->goods_id;
        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $post = \Yii::$app->request->post();
            $goods = Goods::findOne($post['Orders']['goods_id']);
            $transaction = \Yii::$app->db->beginTransaction();
            try {
                //插入订单
                $model->sn = date('YmdHis') . rand(1000, 9999);
                $model->remain_amount = $model->final_amount;
                $model->pay_status = 0;
                $model->ship_status = 1;
                $model->customer_id = $customer->id;
                $model->status = 1;
                $model->item_num = 1;
                $model->ip = (new RequestManage())->getUserIP();
                $model->item_amount = $model->total_amount;
                $model->order_source = 'pc';
                $model->give_points = $goods->score;
                $model->created_at = time();
                $model->order_type = 'conversion';
                $model->associate_id = $order_id;
                $model->telephone = $customer->mobile;
                $model->mechanic_id = $goods->mechanic_id;
                $model->type_id = isset($goods->cate->type_id) ? $goods->cate->type_id : 1;
                $model->save(false);
                ZhtOper::addContinueItem($model, $goods, $customer, $lesson_price, $art_lesson_price);

                $transaction->commit();
                return $this->redirectMessage('转化成功', Fun::url(['customer/details', 'id' => $customer->id]));

            } catch (\Exception $e) {
                $transaction->rollBack();
                return $this->redirectMessage('转化失败', Fun::url(['customer/details', 'id' => $customer->id]));
            }
        }
        return $this->render('transform', ['model' => $model, 'customer' => $customer, 'lesson_price' => $lesson_price, 'account' => $account, 'goods' => $goods, 'goodsAttr' => $attr, 'classTime' => $str, 'artModel' => $artModel, 'artModelLesson' => $artModelLesson]);
    }

    //续费
    public function actionRenew()
    {
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $orders = Orders::findOne($id);
        if ($orders == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '课程信息不存在'));
        }
        $customer = Customer::findOne($orders->customer_id);
        if ($customer == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '会员信息不存在'));
        }

        $orders_item = OrdersItems::find()->where(['orders_id' => $id, 'teach_type' => 1])->one();
        $classgoods = ClassManageGoods::find()->where(['goods_id' => $orders_item->goods_id])->one();
        if ($classgoods == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '班级不存在'));
        }
        $account = CustomerBranchaccount::find()->where(['customer_id' => $customer->id, 'site_id' => Fun::getSiteId()])->one();
        $newClassGoods = ClassManageGoods::find()->where(['class_id' => $classgoods->class_id])->orderBy('goods_id DESC')->limit(1)->one();

        $goods = Goods::findOne($newClassGoods->goods_id);
        if ($goods == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '课程不存在'));
        }

        $goodsPrice = GoodsPrice::find()->where(['goods_id' => $goods->id])->andWhere('price_name != "奖学金课程"')->asArray()->all();
        foreach ($goodsPrice as $key => $price) {
            if ($price['activity_start_time'] <= time() && $price['activity_end_time'] >= time() && $price['effective_number'] > 0) {
                $goodsPrice[$key]['market_price'] = $price['lesson_price'];
            }
            if ($price['is_frequency'] == 0) {
                $goodsPrice[$key]['lesson'] = '不限课次';
            }
        }

        $model = new Orders();
        $model->scenario = 'transform';
        $model->goods_id = $goods->id;
        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $transaction = \Yii::$app->db->beginTransaction();
            $post = \Yii::$app->request->post();
            $price_id = (int)$post['Orders']['goods_price_id'];
            $goods = Goods::findOne($post['Orders']['goods_id']);
            try {
                //插入订单
                $model->sn = date('YmdHis') . rand(1000, 9999);
                $model->remain_amount = $model->final_amount;
                $model->pay_status = 0;
                $model->ship_status = 1;
                $model->payment_id = 2;
                $model->customer_id = $customer->id;
                $model->status = 1;
                $model->item_num = 1;
                $model->ip = (new RequestManage())->getUserIP();
                $model->item_amount = $model->total_amount;
                $model->order_source = 'background';
                $model->give_points = $goods->score;
                $model->created_at = time();
                $model->order_type = 'renew';
                $model->associate_id = $orders->id;
                $model->telephone = $customer->mobile;
                $model->mechanic_id = $goods->mechanic_id;
                $model->type_id = isset($goods->cate->type_id) ? $goods->cate->type_id : 1;
                $model->save(false);
                ZhtOper::perfectOrder($model, $goods, $customer, $price_id);
//                //操作用户金额
//                $option = [
//                    'customer_id' => $customer->id,
//                    'account' => $model->final_amount,
//                    'orders_id' => $model->id,
//                    'note' => '续费订单扣除余额',
//                    'state' => 5
//                ];
//                Account::CustomerAccountReduce($option);
                //修改订单支付状态
//                $orders = Orders::findOne($model->id);
//                $orders->pay_status = 1;
//                $orders->pay_time = time();
//                $orders->cash_money = $model->final_amount;
//                $orders->save(false);
                //减少商品数量
//                $goods->store -= 1;
//                $goods->save(false);
                //增加订单记录
                $log = [
                    'orders_id' => $model->id,
                    'status' => 0,
                    'result' => 'SUCCESS',
                    'log_text' => '管理员下单'
                ];
                ZhtOper::addOrderLog($log);
                $transaction->commit();
                return $this->redirectMessage('续课订单已生成', Fun::url(['customer/details', 'id' => $customer->id]));
            } catch (\Exception $e) {
                $transaction->rollBack();
                return $this->redirectMessage('续费失败', Fun::url(['customer/details', 'id' => $customer->id]));
            }
        }
        return $this->render('renew', ['model' => $model, 'customer' => $customer, 'goods' => $goods, 'account' => $account, 'goodsPrice' => $goodsPrice]);
    }

    //转化/续费订单办理手续
    public function actionContinuepay()
    {
        $order_id = \Yii::$app->request->get('order_id');
        $model = Orders::findOne($order_id);

        if ($model->pay_status == 1) {
            return $this->redirectMessage('此订单已支付！', Fun::url(['customer/details', 'id' => \Yii::$app->request->get('id')]));
        }
        $item = OrdersItems::find()->where(['orders_id' => $order_id, 'teach_type' => 1])->one();
        $AccountRecord = new AccountRecord();
        $AccountRecord->customer_id = $model->customer_id;
        $AccountRecord->scenario = 'orders';
        $account = CustomerBranchaccount::find()->where(['customer_id' => $model->customer_id, 'site_id' => Fun::getSiteId()])->one(); //获取奖学金余额
        $customer_coupons = CustomerCoupons::find()->select(['dmd_coupons.name', 'dmd_coupons.total', 'dmd_coupons.total', 'dmd_coupons.type', 'dmd_customer_coupons.*'])->joinWith('coupons')->where(['customer_id' => $model->customer_id, 'use_status' => 0])->andWhere(['>', 'invalid_time', time()])->asArray()->all();
        $coupons = [];
        if ($customer_coupons) {
            foreach ($customer_coupons as $coupon) {
                if ($coupon['total'] <= $model->final_amount && $coupon['type'] != 'freight') {
                    $row['id'] = $coupon['id'];
                    $row['name'] = $coupon['name'];
                    $coupons[] = $row;
                }
            }
        }
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $AccountRecord->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($AccountRecord);
        }
        if ($AccountRecord->load(\Yii::$app->request->post()) && $AccountRecord->validate()) {
            $total_amount = (float)$model->total_amount;
            $final_amount = (float)$model->final_amount;
            $cash_money = $total_amount;
            $post = \Yii::$app->request->post();
            $discount = isset($post['discount']) ? (int)$post['discount'] : 0;
            $discount_type = isset($post['discount_type']) ? $post['discount_type'] : '';
            $customer_id = isset($post['customer_id']) ? (int)$post['customer_id'] : 0;
            $user_id = $customer_id;
            if ((int)$AccountRecord->cash > 0) {
                $money = (int)$AccountRecord->pay_cash + (int)$AccountRecord->pay_wxpay + (int)$AccountRecord->pay_alipay + (int)$AccountRecord->pay_card;
                $AccountRecord->state = 1;
                $AccountRecord->user_id = \Yii::$app->user->id;
                $AccountRecord->site_id = Fun::getSiteId();
                $AccountRecord->cash = $money;
                $AccountRecord->customer_id = $model->customer_id;
                $AccountRecord->note = '充值';
                if ($AccountRecord->save(false)) {
                    $account->cash += $AccountRecord->cash;
                    $account->save(false);
                }
                Account::addRecharge($model->customer_id, $money);
            }

            $item = OrdersItems::find()->where(['orders_id' => $order_id, 'teach_type' => 1])->one();
            $discount_amount = 0;
            if ($discount_type == 'coupon') {
                $customer_coupon = CustomerCoupons::findOne($discount);
                $coupons = Coupons::findOne($customer_coupon->coupon_id);
                if ($coupons->type == 'full') {
                    $discount_amount = $coupons->amount;
                } else {
                    $discount_amount = $total_amount - ($total_amount * $coupons->amount / 100);
                }
                $final_amount = $total_amount - $discount_amount;
                $cash_money = $total_amount - $discount_amount;
                $total_amount = $total_amount - $discount_amount;
                $paymethod[] = [
                    'pay_code' => 'pay_coupon',
                    'pay_name' => '券支付',
                    'amount' => $discount_amount
                ];
            }
            $account_money = 0;
            $cash = (float)$account->cash;
            if ($total_amount > 0) {
                if ($cash > $total_amount) {
                    $account_money = $total_amount;
                    $cash = $cash - $total_amount;
                } else {
                    $account_money = $cash;
                    $cash = 0;
                }
                $paymethod[] = [
                    'pay_code' => 'pay_account',
                    'pay_name' => '账户余额',
                    'amount' => $account_money
                ];
            }
            $cash_money = 0;
//            if()
            $model->final_amount = $final_amount;
            $model->remain_amount = $final_amount;
            $model->discount_amount = $discount_amount;
            $model->scholarship_money = 0;
            $model->cash_money = $account_money;
            $model->account_money = $account_money;
            $model->pay_status = 1;
            $model->payment_id = 2;
            $model->pay_time = time();
            if ($model->save(false)) {
                $accountModel = new AccountRecord();
                $accountModel->cash = -$account_money;
                $accountModel->customer_id = $model->customer_id;
                $accountModel->site_id = Fun::getSiteId();
                $accountModel->user_id = \Yii::$app->user->id;
                $accountModel->pay_account = -$account_money;
                $accountModel->pay_scholarship = 0;
                $accountModel->state = 5;
                $accountModel->order_id = $model->id;
                $accountModel->note = '转化课程订单扣除余额';
                $accountModel->save(false);
                //减少金额与奖学金
                $account->cash -= $account_money;
                $account->save(false);

                if (!empty($paymethod)) {
                    foreach ($paymethod as $pay) {
                        $paymethodModel = new OrdersSquarePaymethod();
                        $paymethodModel->orders_id = $model->id;
                        $paymethodModel->pay_code = $pay['pay_code'];
                        $paymethodModel->pay_name = $pay['pay_name'];
                        $paymethodModel->amount = $pay['amount'];
                        $paymethodModel->create_at = time();
                        $paymethodModel->save(false);
                    }
                }
                //修改订单商品价格
                Operorders::UpdateOrderItem($order_id, $discount_type, $discount);
                //插入课次以及学生打卡记录表
                Operclassmanager::addclasslesson($model);
                //插入订单操作记录
                $option = [
                    'orders_id' => $model->id,
                    'status' => 2,
                    'result' => 'SUCCESS',
                    'log_text' => '订单支付'
                ];
                Oper::addOrderLog($option);
                //优惠券修改状态
                if ($discount_type == 'coupon') {
                    $customer_coupon->use_status = 1;
                    $customer_coupon->use_time = time();
                    $customer_coupon->save(false);
                }
                //发各类消息
                // \Yii::$app->runAction('customer/sendsysessage',['order_id'=>$order_id]);
                //  \Yii::$app->runAction('customer/sendsysessage',['order_id'=>$order_id,'receiver_type'=>'teache_teacher']);
                //  \Yii::$app->runAction('customer/sendsysessage',['order_id'=>$order_id,'receiver_type'=>'customer']);
                return $this->redirectMessage('设置支付成功', Fun::url(['customer/details', 'id' => $user_id]));
            } else {
                return $this->redirectMessage('设置支付失败', Fun::url(['customer/details', 'id' => $user_id]));
            }

        }

        return $this->render('pay', ['account' => $account, 'coupons' => $coupons, 'model' => $model, 'AccountRecord' => $AccountRecord, 'deposit' => 0]);

    }

    //A模式转化与续费
    public function actionTransfer()
    {
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $type = \Yii::$app->request->get('type');
        $order_item = OrdersItems::findOne(['id' => \Yii::$app->request->get('id')]);
        if ($order_item->orders_id === null || $order_item === null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '课程信息不存在'));
        }
        $customer = Customer::findOne($order_item->orders->customer_id);
        if ($customer === null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '会员信息不存在'));
        }
        $model = new Orders();
        $model->scenario = 'transfer';
        $model->password_r = $customer->password;
        $model->account = $customer->account;
        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $transaction = \Yii::$app->db->beginTransaction();
            $post = \Yii::$app->request->post();
            $goods = Goods::findOne($post['Orders']['goods_id']);
            try {
                //插入订单
                $model->sn = date('YmdHis') . rand(1000, 9999);
                $model->remain_amount = $model->final_amount;
                $model->pay_status = 1;
                $model->pay_time = time();
                $model->ship_status = 1;
                $model->payment_id = 2;
                $model->customer_id = $customer->id;
                $model->status = 1;
                $model->item_num = 1;
                $model->ip = (new RequestManage())->getUserIP();
                $model->item_amount = $model->total_amount;
                $model->order_source = 'pc';
                $model->give_points = $goods->score;
                $model->created_at = time();
                $model->order_type = $type;
                $model->associate_id = $order_item->orders_id;
                $model->telephone = $customer->mobile;
                $model->mechanic_id = $goods->mechanic_id;
                $model->type_id = isset($goods->cate->type_id) ? $goods->cate->type_id : 1;
                $model->save(false);
                ZhtOper::perfectOrder($model, $goods, $customer);
                //减少商品数量
                //操作用户金额
                $option = [
                    'customer_id' => $customer->id,
                    'account' => $model->final_amount,
                    'orders_id' => $model->id,
                    'note' => '续费订单扣除余额',
                    'state' => 5
                ];
                Account::CustomerAccountReduce($option);
                //修改订单支付状态
                $orders = Orders::findOne($model->id);
                $orders->pay_status = 1;
                $orders->pay_time = time();
                $orders->cash_money = $model->final_amount;
                $orders->save(false);

                //增加订单记录
                $log = [
                    'orders_id' => $model->id,
                    'status' => 2,
                    'result' => 'SUCCESS',
                    'log_text' => '订单支付'
                ];
                ZhtOper::addOrderLog($log);
                $transaction->commit();
                return $this->redirectMessage('操作成功', Fun::url(['customer/details', 'id' => $customer->id]));
            } catch (\Exception $e) {
                $transaction->rollBack();
                return $this->redirectMessage('操作失败', Fun::url(['customer/details', 'id' => $customer->id]));
            }

        }

        return $this->render('transform', ['model' => $model, 'customer' => $customer, 'order_item' => $order_item]);
    }

    //线下购买商品
    public function actionOrderproduct()
    {
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $session = \Yii::$app->session;
        $id = \Yii::$app->request->get('id');
        $customer = Customer::findOne($id);
        $model = new Orders();
        $model->customer_id = $id;
        $model->scenario = 'orderproduct';
        $branchaccount = CustomerBranchaccount::find()->where(['customer_id' => $id, 'site_id' => Fun::getSiteId()])->one();
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $post = \Yii::$app->request->post();
            $goods_ids = $post['Orders']['goods_id'];
            $gids = explode(',', $goods_ids);
            $score = Goods::find()->where(['id' => $gids])->sum('score');
            $goods = Goods::findOne($gids[0]);
            $cartArr = $session->get('cart');
            $num = 0;
            foreach ($cartArr[1] as $val) {
                $num += (int)$val;
            }

            $model->sn = date('YmdHis') . rand(1000, 9999);
            $model->total_amount = $model->final_amount;
            $model->remain_amount = $model->final_amount;
            $model->pay_status = 0;
            $model->pay_time = 0;
            $model->ship_status = 1;
            $model->payment_id = 2;
            $model->customer_id = $customer->id;
            $model->status = 1;
            $model->item_num = $num;
            $model->ip = (new RequestManage())->getUserIP();
            $model->item_amount = $model->total_amount;
            $model->order_source = 'background';
            $model->give_points = $score;
            $model->created_at = time();
            $model->order_type = 'goods';
            $model->telephone = $customer->mobile;
            $model->cash_money = $model->final_amount;
            $model->account_money = $model->final_amount;
            $model->customer_card = $customer->card_id;
            $model->mechanic_id = $goods->mechanic_id;
            $model->type_id = isset($goods->cate->type_id) ? $goods->cate->type_id : 1;
            $model->save(false); //创建订单

            ZhtOper::addorderitem($model, $cartArr);//插入订单商品

//            $option = [
//                'customer_id' => $customer->id,
//                'account' => $model->final_amount,
//                'orders_id' => $model->id,
//                'note' => '下单减少余额',
//                'state' => 5
//            ];
//            //减少会员余额并生成记录
//            if (Account::CustomerAccountReduce($option)) {
//                $order = Orders::findOne($model->id);
//                $order->pay_status = 2;
//                $order->pay_time = time();
//                $order->status = 6;
//                $order->save(false);
//
//                //插入日志
//                $data = [
//                    'orders_id' => $model->id,
//                    'status' => 2,
//                    'result' => 'SUCCESS',
//                    'log_text' => '订单支付'
//                ];
//                ZhtOper::addOrderLog($data);
//            }
            $session->remove('cart');
            return $this->redirectMessage('操作成功', Fun::url(['customer/details', 'id' => \Yii::$app->request->get('id')]));

        } else {
//            print_r($model->getErrors());

            $session->remove('cart');
        }
        return $this->render('orderproduct', ['account' => $branchaccount, 'customer' => $customer, 'model' => $model]);
    }

    public function actionPayproduct()
    {
        $order_id = \Yii::$app->request->get('id');
        $model = Orders::findOne($order_id);
        $account = CustomerBranchaccount::find()->where(['customer_id' => $model->customer_id, 'site_id' => Fun::getSiteId()])->one(); //获取奖学金余额
        $item = OrdersItems::find()->where(['orders_id' => $model->id])->one();
        $goods = Goods::findOne($item->goods_id);
        $AccountRecord = new AccountRecord();
        $AccountRecord->customer_id = $model->customer_id;
        $AccountRecord->scenario = 'payproduct';
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $AccountRecord->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($AccountRecord);
        }

        if ($AccountRecord->load(\Yii::$app->request->post()) && $AccountRecord->validate()) {
            $cash = (float)$AccountRecord->cash;
            $money = (float)$AccountRecord->money;
            if ((float)$AccountRecord->money > 0) {
                $moneys = (float)$AccountRecord->pay_cash + (float)$AccountRecord->pay_wxpay + (float)$AccountRecord->pay_alipay + (float)$AccountRecord->pay_card;
                $AccountRecord->state = 1;
                $AccountRecord->user_id = \Yii::$app->user->id;
                $AccountRecord->site_id = Fun::getSiteId();
                $AccountRecord->cash = $moneys;
                $AccountRecord->customer_id = $model->customer_id;
                $AccountRecord->note = '充值';
                if ($AccountRecord->save(false)) {
                    $account->cash += $moneys;
                    $account->save(false);
                }
                Account::addRecharge($model->customer_id, $money);
            }
            $model->pay_status = 1;
            $model->payment_id = 2;
            $model->pay_time = time();

            if ($model->save(false)) {
                $accountModel = new AccountRecord();
                $accountModel->cash = -$model->total_amount;
                $accountModel->customer_id = $model->customer_id;
                $accountModel->site_id = Fun::getSiteId();
                $accountModel->user_id = \Yii::$app->user->id;
                $accountModel->pay_account = -$model->total_amount;
                $accountModel->state = 5;
                $accountModel->order_id = $model->id;
                $accountModel->note = '实物订单扣除余额';
                $accountModel->save(false);


                $p_cash = (float)$AccountRecord->p_cash;
                $pay_code = '';
                if ($p_cash > 0) {
                    if ($goods->category_id == 1) {
                        $pay_code = 'puzzle_cash';
                        $p_name = '益智专用金额';
                    }
                    if ($goods->category_id == 2) {
                        $pay_code = 'music_cash';
                        $p_name = '音乐专用金额';
                    }
                    if ($goods->category_id == 3) {
                        $pay_code = 'body_cash';
                        $p_name = '形体专用金额';
                    }
                    $paymethod[] = [
                        'pay_code' => $pay_code,
                        'pay_name' => $p_name,
                        'amount' => $p_cash
                    ];
                }
                if (($cash + $money) > 0) {
                    $paymethod[] = [
                        'pay_code' => 'pay_account',
                        'pay_name' => '账户余额',
                        'amount' => $cash + $money
                    ];
                }
                //减少金额与奖学金
                $account->cash -= $cash + $money;
                if ($pay_code != '') {
                    $account->$pay_code -= $p_cash;
                }
                $account->save(false);

                if (!empty($paymethod)) {
                    foreach ($paymethod as $pay) {
                        $paymethodModel = new OrdersSquarePaymethod();
                        $paymethodModel->orders_id = $model->id;
                        $paymethodModel->pay_code = $pay['pay_code'];
                        $paymethodModel->pay_name = $pay['pay_name'];
                        $paymethodModel->amount = $pay['amount'];
                        $paymethodModel->create_at = time();
                        $paymethodModel->save(false);
                    }
                }
                //插入订单操作记录
                $option = [
                    'orders_id' => $model->id,
                    'status' => 2,
                    'result' => 'SUCCESS',
                    'log_text' => '订单支付'
                ];
                Oper::addOrderLog($option);
                return $this->redirectMessage('支付成功', Fun::url(['customer/details', 'id' => $model->customer_id]));
            } else {
                return $this->redirectMessage('支付失败', Fun::url(['customer/details', 'id' => $model->customer_id]));
            }
        }
        return $this->render('payproduct', ['model' => $model, 'account' => $account, 'goods' => $goods, 'AccountRecord' => $AccountRecord]);
    }

    public function actionParcash()
    {
        $post = \Yii::$app->request->post();
        \Yii::$app->response->format = Response::FORMAT_JSON;
        if (empty($post['order_id']) || empty($post['customer_id'])) {
            return ['status' => 0, 'content' => '系统错误请重试！'];
        }
        $type = $post['type'];
        $model = Orders::findOne($post['order_id']);
        $account = CustomerBranchaccount::find()->where(['customer_id' => $model->customer_id, 'site_id' => Fun::getSiteId()])->one(); //获取奖学金余额
        $money = 0; //需支付现金
        $cash = 0; //扣除账户余额
        $type_cash = 0; //扣除类型金额
        $str = '';
        if ($post['checked'] == 0) {
            // $money = $model->total_amount;
            if ($account->cash > 0) {
                if ($model->total_amount >= $account->cash) {
                    $money = $model->total_amount - $account->cash;
                    $cash = $account->cash;
                } else {
                    $cash = $model->total_amount;
                }
            } else {
                $money = $model->total_amount;
            }
            if ($cash > 0) {
                $str .= '扣除余额：' . number_format($cash, 2) . '<br>';
            }
            if ($money > 0) {
                $str .= '需支付现金：' . number_format($money, 2);
            }
            return ['status' => 1, 'content' => $str, 'data' => ['cash' => $cash, 'money' => $money, 'type_cash' => $type_cash]];
        }
        if ($post['checked'] == 1) {
            if ($account->$type >= $model->total_amount) {
                $type_cash = $model->total_amount;
            } else {
                $type_cash = $account->$type;
                if ($account->cash > 0) {
                    if ($model->total_amount - $type_cash > $account->cash) {
                        $cash = $account->cash;
                        $money = $model->total_amount - $type_cash - $cash;
                    } else {
                        $cash = $model->total_amount - $type_cash;
                    }
                } else {
                    $money = $model->total_amount - $type_cash;
                }
            }
            if ($type_cash > 0) {
                $str .= '扣除类型金额：' . number_format($type_cash, 2) . '<br>';
            }
            if ($cash > 0) {
                $str .= '扣除余额：' . number_format($cash, 2) . '<br>';
            }
            if ($money > 0) {
                $str .= '需支付现金：' . number_format($money, 2);
            }
            return ['status' => 1, 'content' => $str, 'data' => ['cash' => $cash, 'money' => $money, 'type_cash' => $type_cash]];
        }
    }

    //实物商品搜索
    public function actionSearch()
    {
        \Yii::$app->response->format = Response::FORMAT_JSON;
        $post = \Yii::$app->request->post();
        $where = ['type_id' => [2, 4, 6], 'is_buy' => 1, 'is_delete' => 0];
        if (!empty($post['type_id'])) {
            $where['type_id'] = $post['type_id'];
        }
        $model = Goods::find();
        $model->where($where);
        if (!empty($post['goods_name'])) {
            $model->andWhere(['like', 'name', $post['goods_name']]);
        }
        $res = $model->all();
        $ajax_object = new AjaxObject();
        $ajax_object->data = Fun::asArray($res, []);
        return $ajax_object;
    }

    //获取单个商品
    public function actionGoodsinfo()
    {
        \Yii::$app->response->format = Response::FORMAT_JSON;
        $post = \Yii::$app->request->post();
        $goods_id = (int)$post['goods_id'];
        $num = (int)$post['num'];
        $goods = Goods::find()->where(['id' => $goods_id])->asArray()->one();
        if ($goods) {
            $goods['subtotal'] = $goods['price'] * $num;
        }
        $session = \Yii::$app->session;
        $arrDatax[0][$goods_id] = $goods_id; //商品id
        $arrDatax[1][$goods_id] = $num; //数量
        $arrDatax[2][$goods_id] = $goods['subtotal']; //数量
        if (!$session->get('cart')) {
            $session->set('cart', $arrDatax);
        } else {
            $arrDataz = $session->get('cart');
            if (in_array($goods_id, $arrDataz[0])) {
                $arrDataz[1][$goods_id] += $num;
                $arrDataz[2][$goods_id] += $goods['subtotal'];
                $session->set('cart', $arrDataz);
            } else {
                $arrDataz[0][$goods_id] = $goods_id;
                $arrDataz[1][$goods_id] = $num;
                $arrDataz[2][$goods_id] = $goods['subtotal'];;
                $session->set('cart', $arrDataz);
            }
        }

        $arr = $session->get('cart');
        $list = Goods::find()->where(['id' => $arr[0]])->all();
        $data = [];
        $total = 0;
        foreach ($list as $val) {
            $row = [
                'id' => $val->id,
                'name' => $val->name,
                'price' => $val->price,
                'store' => $val->store,
                'num' => $arr[1][$val->id],
                'subtotal' => $arr[2][$val->id],
            ];
            $total += $arr[2][$val->id];
            $data[] = $row;
        }
        $ajax_object = new AjaxObject();
        $ajax_object->data = $data;
        $ajax_object->content = $total;
        $ajax_object->pages = implode(',', $arr[0]);
        return $ajax_object;

    }

    //移除商品
    public function actionRemove()
    {
        \Yii::$app->response->format = Response::FORMAT_JSON;
        $id = \Yii::$app->request->post('id');
        $arr = \Yii::$app->session->get('cart');
        unset($arr[0][$id]);
        unset($arr[1][$id]);
        unset($arr[2][$id]);
        $newarr = [];
        if (count($arr[0]) == 0) {
            \Yii::$app->session->remove('cart');
        } else {
            \Yii::$app->session->set('cart', $arr);
            $newarr = \Yii::$app->session->get('cart');
        }
        $ajax_object = new AjaxObject();
        $ajax_object->data = null;
        $ajax_object->content = 0;
        $ajax_object->pages = '';
        if ($newarr) {
            $list = Goods::find()->where(['id' => $newarr[0]])->all();
            $data = [];
            $total = 0;
            foreach ($list as $val) {
                $row = [
                    'id' => $val->id,
                    'name' => $val->name,
                    'price' => $val->price,
                    'store' => $val->store,
                    'num' => $arr[1][$val->id],
                    'subtotal' => $arr[2][$val->id],
                ];
                $total += $arr[2][$val->id];
                $data[] = $row;
            }
            $ajax_object->data = $data;
            $ajax_object->content = $total;
            $ajax_object->pages = implode(',', $newarr[0]);;
        }
        return $ajax_object;
    }

    public function actionChose()
    {
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'chose') {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $sales_id = \Yii::$app->request->post('sales_id');
            if (\Yii::$app->request->post('customer_id') == null || \Yii::$app->request->post('sales_id') == null || \Yii::$app->request->post('ordercourse_history_id') == null) {
                throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
            }
            $customer = Customer::findOne(\Yii::$app->request->post('customer_id'));
            $ordercourse_history = OrdercourseHistory::findOne(\Yii::$app->request->post('ordercourse_history_id'));
            $sales = Sales::findOne(\Yii::$app->request->post('sales_id'));
            if ($customer == null || $ordercourse_history == null || $sales == null) {
                throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
            }
            $order_sales = OrderSales::findOne($ordercourse_history->order_sales_id);
            $order = Order::find()->where(['id' => $order_sales->order_id])->asArray()->one();
            //order表
            $id = ArrayHelper::remove($order, 'id');
            $order['order_number'] = 'xk' . str_pad(Fun::getSiteId(), 4, "0", STR_PAD_LEFT) . time();
            $order['total'] = 0;
            $order['user_id'] = \Yii::$app->user->id;
            $order['create_at'] = time();
            $order['ip'] = \Yii::$app->request->getUserIp();
            $order['pay_cash'] = 0;
            $order['pay_pos'] = 0;
            $order['pay_card'] = 0;
            $order['discount_pay'] = 0;
            $order['actual_pay'] = 0;
            $order['associate_id'] = $id;
            $order['is_appointment'] = 1;
            $chose_order = new Order();
            $chose_order->attributes = $order;
            if ($chose_order->save(false)) {
                //sales表
                $update_sales = Sales::findOne(['id' => $sales_id]);
                if ($update_sales != null) {
                    $update_sales->total_stock -= 1;
                    $update_sales->save(false);
                }
                //order_sales表
                $chose_sales = Sales::find()->where(['id' => $sales_id])->asArray()->one();
                $sales_model = Sales::find()->where(['id' => $sales_id])->one();
                if (!isset($sales_model->arrangeCourse) || !isset($sales_model->classroomAttr)) {
                    throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
                }
                $arrange_course = $sales_model->arrangeCourse;
                $classroom_attr = $sales_model->classroomAttr;
                $ids = ArrayHelper::remove($chose_sales, 'id');
                $chose_sales['order_id'] = $chose_order->id;
                ArrayHelper::remove($chose_sales, 'total_stock');
                ArrayHelper::remove($chose_sales, 'created_at');
                ArrayHelper::remove($chose_sales, 'is_book');
                ArrayHelper::remove($chose_sales, 'status');
                ArrayHelper::remove($chose_sales, 'classroom_attr_id');
                ArrayHelper::remove($chose_sales, 'teacher_img');
                ArrayHelper::remove($chose_sales, 'teache_form');
                $chose_sales['price'] = $arrange_course->price;
                $chose_sales['class_length'] = $arrange_course->class_length;
                $chose_sales['class_count'] = $arrange_course->class_count;
                $chose_sales['max_number'] = $arrange_course->max_number;
                $chose_sales['opening_number'] = $arrange_course->opening_number;
                $chose_sales['class_day'] = $classroom_attr->classday;
                $chose_sales['start_time'] = $classroom_attr->start_time;
                $chose_sales['end_time'] = $classroom_attr->end_time;
                $chose_sales['created_at'] = time();
                $chose_sales['sales_id'] = $ids;
                $chose_sales['number'] = 1;
                $chose_sales['can_back_number'] = 1;
                $chose_sales['student_id'] = $order_sales->student_id;
                $chose_ordersales = new OrderSales($chose_sales);
                if ($chose_ordersales->save(false)) {
                    //class_manage表
                    $classmanage = ClassManage::findOne(['code' => $chose_ordersales->arrange_course_id]);
                    if ($classmanage === null) {
                        $class_manage = new ClassManage();
                        $class_manage->class_code = 'c' . time();
                        $class_manage->code = $chose_ordersales->arrange_course_id;
                        if ($class_manage->save(false)) {
                            //class_student表
                            $class_student = new ClassStudent();
                            $class_student->class_manage_id = $class_manage->class_id;
                            $class_student->student_id = $chose_ordersales->student_id;
                            $class_student->order_sales_id = $chose_ordersales->id;
                            $class_student->save(false);
                        }
                    } else {
                        //class_student表
                        $class_student = new ClassStudent();
                        $class_student->class_manage_id = $classmanage->class_id;
                        $class_student->student_id = $chose_ordersales->student_id;
                        $class_student->order_sales_id = $chose_ordersales->id;
                        $class_student->save(false);
                    }
                    //order_course_history表
                    $ordercourse_history->order_sales_id = $chose_ordersales->id;
                    $ordercourse_history->course_id = $chose_ordersales->course_id;
                    $ordercourse_history->status = 1;
                    //order_history
                    $old_orderhistory = new OrderHistory();
                    $old_orderhistory->order_id = $chose_order->associate_id;
                    $old_orderhistory->states = 17;//被选课
                    $orderhistory = new OrderHistory();
                    $orderhistory->order_id = $chose_order->id;
                    $orderhistory->states = 18;//选课
                    if ($old_orderhistory->save(false) && $orderhistory->save(false) && $ordercourse_history->save(false)) {
                        return '选课成功';
                    }
                }
            }
        }
    }

    //交保证金
    public function actionDeposit()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $customer_id = \Yii::$app->request->get('id');
        $item_id = \Yii::$app->request->get('item_id');
        $items = OrdersItems::findOne($item_id);
        if ($items === null || $items->student_id == 0) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        if (Fun::getSiteMode(Fun::getSiteId()) == 'A') {
            $res = DepositLog::find()->where(['status' => 0, 'customer_id' => $customer_id])->one();
        } else {
            $res = DepositLog::find()->where(['status' => 0, 'customer_id' => $customer_id, 'orders_items_id' => $item_id])->one();
        }
        if ($res != null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '保证金已交'));
        }
        $customer = Customer::findOne($customer_id);
        $model = new AccountRecord();
        $form = new BuildForm('@app/components/forms/accountrecordchargeForm.php');
        $form->loadModel(['accountrecord' => $model]);
        $form->loadDefaultValues();
        if ($form->loadData(\Yii::$app->request->post()) && $form->validate()) {
            $account = (int)$model->pay_cash + (int)$model->pay_pos + (int)$model->free;
            $customer->deposit = +$account;
            $transaction = \Yii::$app->db->beginTransaction();
            try {
                $customer->save(false);
                $model->customer_id = $customer_id;
                $model->cash = $account;
                $model->site_id = Fun::getSiteId();
                $model->user_id = \Yii::$app->user->id;
                $model->created_at = time();
                $model->deposit = $account;
                $model->state = 4;
                $model->order_id = $items->orders_id;
                $model->note = '交保证金';
                $model->save(false);

                $depositLog = new DepositLog();
                $depositLog->customer_id = $customer_id;
                $depositLog->site_id = Fun::getSiteId();
                $depositLog->orders_id = $items->orders_id;
                $depositLog->orders_items_id = $item_id;
                $depositLog->mode = Fun::getSiteMode(Fun::getSiteId());
                $depositLog->money = $account;
                $depositLog->pay_type = 1;
                $depositLog->created_at = time();
                $depositLog->code = date('YmdHis') . rand(10, 99);
                $depositLog->save();

                //获取课程课次
                $classstudent = ClassStudent::find()->where(['order_sales_id' => $item_id])->one();
                if ($classstudent->status == 1) {
                    $student_check = [];
                    $goodsattr = GoodsAttr::find()->where(['goods_id' => $items->goods_id, 'obj_type' => 'class_count'])->one();
                    $count = (int)$goodsattr->value;
                    for ($i = 1; $i <= $count; $i++) {
                        if ($count > floor($count / 3)) {
                            $student_check[$i]['class_student_id'] = $classstudent->id;
                            $student_check[$i]['order_sales_id'] = $item_id;
                            $student_check[$i]['student_id'] = $items->student_id;
                            $student_check[$i]['status'] = null;
                            $student_check[$i]['created_at'] = null;
                            $class_lesson_id = ClassLesson::findOne(['class_id' => $classstudent->class_manage_id, 'lesson' => $i]);
                            $student_check[$i]['class_lesson_id'] = $class_lesson_id->lesson_id;
                        }
                    }
                    Fun::getSiteDb()->createCommand()->batchInsert('{{%student_check}}', ['class_student_id', 'order_sales_id', 'student_id', 'status', 'created_at', 'class_lesson_id'], $student_check)->execute();
                }

                $transaction->commit();
                return $this->redirectMessage('交保证金成功', Fun::url(['customer/details', 'id' => $customer->id]));
            } catch (\Exception $e) {
                $transaction->rollBack();
                return $this->redirectMessage('交保证金失败', Fun::url(['customer/details', 'id' => $customer->id]));
            }
        }
        return $this->render('deposit', ['form' => $form->render(), 'customer' => $customer]);
    }

    //课时
    public function actionClasshour()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $orderitem = OrdersItems::findOne($id);
        if ($orderitem == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $classstudent = ClassStudent::find()->where(['order_sales_id' => $id, 'student_id' => $orderitem->student_id])->one();
        if ($classstudent == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $classmanage = ClassManage::findOne($classstudent->class_manage_id);
        if ($classmanage == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '班级不存在'));
        }
        if ($classmanage->status == 0) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '未开课'));
        }
        $classhour = StudentCheck::findAll(['student_id' => $orderitem->student_id, 'class_student_id' => $classstudent->id]);
        $data = [];
        foreach ($classhour as $k => $val) {
            $data[$k]['title'] = isset($val->classlesson) ? $val->classlesson->title : '';
            $data[$k]['class_date'] = isset($val->classlesson) ? \Yii::$app->formatter->asDate($val->classlesson->class_date) : '';
            $data[$k]['time'] = isset($val->classlesson) ? \common\components\helpers\Fun::getClassTime($val->classlesson->start_time, $val->classlesson->end_time) : '';
            $data[$k]['lesson'] = isset($val->classlesson) ? $val->classlesson->lesson : '';
//            $now = time();
//            $start_second = (int)substr($val->classlesson->start_time, 2);
//            $end_second = (int)substr($val->classlesson->end_time, 2);
//            if(strlen($val->classlesson->start_time) == 3){
//                $start_second = (int)substr($val->classlesson->start_time, 1);
//            }
//            if(strlen($val->classlesson->end_time) == 3){
//                $end_second = (int)substr($val->classlesson->end_time, 1);
//            }
//            $class_length = (floor($val->classlesson->start_time / 100) - floor($val->classlesson->end_time / 100)) * 60 + ($end_second-$start_second);
//            $endtime = $val->classlesson->class_date+7200+$class_length*60;
            $classDate = date('Y-m-d', $val->classlesson->class_date);
            $nowDate = date('Y-m-d', time());
            if ($val->status == 0 && ($classDate < $nowDate)) {
                $status_name = '旷课';
            } elseif ($val->status == 1) {
                $status_name = '已上课';
            } elseif ($val->status == 2) {
                $status_name = '请假';
            } elseif ($val->status == 3) {
                $status_name = '已退课';
            } else {
                $status_name = '未上课';
            }
            $data[$k]['status_name'] = $status_name;
        }

        return $this->render('lesson', ['details' => $data]);

    }

//    /*
//     * 清空*/
//    public function actionTruncatetable(){
//        $truncate_tables = ['class_lesson','class_student','customer_address','lesson_student','orders','orders_activity_log','orders_items','orders_log','orders_type','student_check','substitute_check'];
//        foreach ($truncate_tables as $table){
//            $result = Fun::getSiteDb()->createCommand()->truncateTable('{{%'.$table.'}}')->execute();
//            echo $table.':'.$result.'<br>';
//        }
//        return;
//    }
//
//    /*
//     * 清空*/
//    public function actionDeletemanage(){
//        $classm = ClassManage::find()->where(['status'=>[1,2]])->all();
//        $i = 0;
//        foreach($classm as $c){
//            if($c->delete()){
//                if($c->is_old == 0) {
//                    $goods = Goods::findOne($c->associate_id);
//                    if ($goods) {
//                        $goods->delete();
//                        GoodsAttr::deleteAll(['goods_id' => $goods->id]);
//                        GoodsClassTime::deleteAll(['goods_id' => $goods->id]);
//                    }
//                }else{
//                    $aModel = Arrangement::findOne($c->associate_id);
//                    if($aModel)
//                        $aModel->delete();
//                }
//                $i++;
//                echo $i;
//            }
//        }
//        return;
//    }

    function diffDate($date1, $date2)
    {
        if (strtotime($date1) > strtotime($date2)) {
            $tmp = $date2;
            $date2 = $date1;
            $date1 = $tmp;
        }
        list($Y1, $m1, $d1) = explode('-', $date1);
        list($Y2, $m2, $d2) = explode('-', $date2);
        $y = $Y2 - $Y1;
        $m = $m2 - $m1;
        $d = $d2 - $d1;
        if ($d < 0) {
            $d += (int)date('t', strtotime("-1 month $date2"));
            $m--;
        }
        if ($m < 0) {
            $m += 12;
            $y--;
        }
        return $y;
    }

    public function actionReset()
    {
        $id = \Yii::$app->request->get('id');

        if ($id == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        //卡信息的删除
        $card_attr = CardAttr::findOne(['customer_id' => $id]);
        if (!empty($card_attr)) {
            $cardbatch = CardBatch::find()->where(['id' => $card_attr->batch_id])->one();
            if ($cardbatch != null || $cardbatch->number > 1) {
                throw new BadRequestHttpException(\Yii::t('zhtfrontend', '所属卡批次申请数量必须为1，否则无法使用该功能！'));
            } else {
                CardBatch::deleteAll(['id' => $card_attr->batch_id]);
                Card::updateAll(['status' => 1], ['id' => $card_attr->card_id]);
                $card_send = CardSend::findOne(['batch_id' => $card_attr->batch_id]);
                if ($card_send != null) {
                    CardReSend::deleteAll(['card_send_id' => $card_send->id]);
                    $card_send->delete();
                }
            }
        }

        // 订单信息的删除
        $orders = Orders::find()->select('id')->where(['customer_id' => $id])->column();
        if ($orders != null) {
            OrdersType::deleteAll(['in', 'orders_id', $orders]);
            Orders::deleteAll(['in', 'id', $orders]);
            $ordersItems = OrdersItems::find()->select('id')->where(['in', 'orders_id', $orders])->column();
            ClassStudent::deleteAll(['in', 'order_sales_id', $ordersItems]);
            StudentCheck::deleteAll(['in', 'order_sales_id', $ordersItems]);
            $student = Student::findOne(['customer_id' => $id]);
            if ($student != null) {
                LessonStudent::deleteAll(['student_id' => $student->id]);
            }
            AccountRecord::deleteAll(['customer_id' => $id]);
            DepositLog::deleteAll(['customer_id' => $id]);
            CustomerDues::deleteAll(['customer_id' => $id]);
            OrdersItems::deleteAll(['in', 'id', $ordersItems]);
        }
        return $this->redirectMessage('重置成功', Fun::url(['customer/details', 'id' => \Yii::$app->request->get('id')]));
    }


}